From 4b1a9203c547c019fc5398082ae19a3f3d4c3efe Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:41:15 -0500 Subject: initial commit --- files/de/web/api/aescbcparams/index.html | 52 + files/de/web/api/animationevent/index.html | 190 ++ .../api/audiocontext/decodeaudiodata/index.html | 218 ++ files/de/web/api/audiocontext/index.html | 232 ++ files/de/web/api/audiodestinationnode/index.html | 141 + files/de/web/api/audionode/index.html | 191 ++ files/de/web/api/audiotrack/index.html | 86 + files/de/web/api/battery_status_api/index.html | 92 + files/de/web/api/blob/index.html | 245 ++ files/de/web/api/body/arraybuffer/index.html | 87 + files/de/web/api/body/blob/index.html | 73 + files/de/web/api/body/body/index.html | 86 + files/de/web/api/body/bodyused/index.html | 73 + files/de/web/api/body/formdata/index.html | 62 + files/de/web/api/body/index.html | 99 + files/de/web/api/body/json/index.html | 73 + files/de/web/api/body/text/index.html | 80 + files/de/web/api/cache/add/index.html | 106 + files/de/web/api/cache/addall/index.html | 212 ++ files/de/web/api/cache/index.html | 288 ++ .../api/canvasrenderingcontext2d/canvas/index.html | 56 + .../canvasrenderingcontext2d/fillrect/index.html | 177 ++ .../getimagedata/index.html | 142 + .../de/web/api/canvasrenderingcontext2d/index.html | 432 +++ .../ispointinpath/index.html | 206 ++ .../api/canvasrenderingcontext2d/scale/index.html | 223 ++ .../setlinedash/index.html | 179 ++ .../canvasrenderingcontext2d/textalign/index.html | 128 + files/de/web/api/childnode/index.html | 190 ++ files/de/web/api/childnode/remove/index.html | 97 + files/de/web/api/console/assert/index.html | 98 + files/de/web/api/console/clear/index.html | 49 + files/de/web/api/console/count/index.html | 103 + files/de/web/api/console/debug/index.html | 63 + files/de/web/api/console/dir/index.html | 56 + files/de/web/api/console/index.html | 296 ++ files/de/web/api/console/log/index.html | 180 ++ files/de/web/api/console/table/index.html | 214 ++ files/de/web/api/console/time/index.html | 56 + files/de/web/api/console/timeend/index.html | 57 + files/de/web/api/console/warn/index.html | 147 + files/de/web/api/crypto/index.html | 68 + files/de/web/api/css/escape/index.html | 79 + files/de/web/api/css/index.html | 90 + files/de/web/api/css_painting_api/guide/index.html | 534 ++++ files/de/web/api/css_painting_api/index.html | 199 ++ files/de/web/api/cssmediarule/index.html | 120 + files/de/web/api/csspagerule/index.html | 129 + files/de/web/api/cssrule/csstext/index.html | 31 + files/de/web/api/cssrule/index.html | 258 ++ .../api/customelementregistry/define/index.html | 241 ++ files/de/web/api/customelementregistry/index.html | 106 + .../web/api/dedicatedworkerglobalscope/index.html | 114 + .../message_event/index.html | 83 + files/de/web/api/document/adoptnode/index.html | 53 + files/de/web/api/document/alinkcolor/index.html | 30 + files/de/web/api/document/body/index.html | 140 + .../de/web/api/document/createattribute/index.html | 76 + .../api/document/createdocumentfragment/index.html | 137 + files/de/web/api/document/createelement/index.html | 153 + .../de/web/api/document/createelementns/index.html | 175 ++ .../de/web/api/document/createtextnode/index.html | 131 + .../web/api/document/createtreewalker/index.html | 241 ++ files/de/web/api/document/dir/index.html | 95 + files/de/web/api/document/document/index.html | 45 + .../de/web/api/document/documentelement/index.html | 42 + .../api/document/fullscreenchange_event/index.html | 87 + .../de/web/api/document/getelementbyid/index.html | 131 + .../api/document/getelementsbyclassname/index.html | 105 + files/de/web/api/document/head/index.html | 73 + files/de/web/api/document/importnode/index.html | 93 + files/de/web/api/document/index.html | 405 +++ files/de/web/api/document/queryselector/index.html | 129 + .../web/api/document/queryselectorall/index.html | 172 ++ files/de/web/api/document/readystate/index.html | 111 + files/de/web/api/document/referrer/index.html | 46 + .../de/web/api/document/registerelement/index.html | 113 + files/de/web/api/document/title/index.html | 70 + files/de/web/api/document/url/index.html | 19 + files/de/web/api/document/width/index.html | 45 + files/de/web/api/document/write/index.html | 85 + files/de/web/api/document/writeln/index.html | 60 + files/de/web/api/documentfragment/index.html | 258 ++ files/de/web/api/domerror/index.html | 189 ++ files/de/web/api/domparser/index.html | 181 ++ files/de/web/api/domstring/index.html | 57 + files/de/web/api/domtokenlist/add/index.html | 73 + files/de/web/api/domtokenlist/index.html | 125 + files/de/web/api/dragevent/index.html | 239 ++ files/de/web/api/element/classlist/index.html | 300 ++ files/de/web/api/element/classname/index.html | 128 + .../api/element/getboundingclientrect/index.html | 62 + files/de/web/api/element/hasattribute/index.html | 129 + files/de/web/api/element/index.html | 522 ++++ files/de/web/api/element/innerhtml/index.html | 204 ++ .../web/api/element/insertadjacenthtml/index.html | 144 + files/de/web/api/element/queryselector/index.html | 89 + .../de/web/api/element/queryselectorall/index.html | 206 ++ .../de/web/api/element/removeattribute/index.html | 42 + .../web/api/element/requestfullscreen/index.html | 118 + files/de/web/api/element/scrollintoview/index.html | 85 + files/de/web/api/element/scrollleft/index.html | 83 + files/de/web/api/element/scrollwidth/index.html | 49 + files/de/web/api/element/setattribute/index.html | 48 + files/de/web/api/event/bubbles/index.html | 59 + files/de/web/api/event/event/index.html | 72 + files/de/web/api/event/index.html | 253 ++ files/de/web/api/eventlistener/index.html | 48 + files/de/web/api/eventsource/index.html | 126 + files/de/web/api/eventtarget/index.html | 174 ++ files/de/web/api/federatedcredential/index.html | 125 + files/de/web/api/fetch_api/index.html | 84 + files/de/web/api/file/filename/index.html | 35 + files/de/web/api/file/filesize/index.html | 36 + files/de/web/api/file/getastext/index.html | 78 + files/de/web/api/file/index.html | 146 + files/de/web/api/file/name/index.html | 104 + files/de/web/api/file/typ/index.html | 65 + .../index.html | 512 ++++ files/de/web/api/filereader/index.html | 153 + files/de/web/api/filereader/onload/index.html | 24 + files/de/web/api/formdata/formdata/index.html | 184 ++ files/de/web/api/formdata/get/index.html | 145 + files/de/web/api/formdata/getall/index.html | 74 + files/de/web/api/formdata/index.html | 80 + files/de/web/api/fullscreenoptions/index.html | 43 + files/de/web/api/gainnode/index.html | 134 + files/de/web/api/gamepad_api/index.html | 95 + .../api/geolocation/getcurrentposition/index.html | 88 + files/de/web/api/geolocation/index.html | 71 + files/de/web/api/globaleventhandlers/index.html | 540 ++++ .../web/api/globaleventhandlers/onclick/index.html | 88 + .../web/api/globaleventhandlers/onload/index.html | 150 + .../api/globaleventhandlers/onresize/index.html | 77 + files/de/web/api/htmlcanvaselement/index.html | 242 ++ .../web/api/htmlcanvaselement/todataurl/index.html | 206 ++ .../webglcontextcreationerror_event/index.html | 132 + .../webglcontextlost_event/index.html | 133 + .../webglcontextrestored_event/index.html | 135 + files/de/web/api/htmlcollection/index.html | 70 + .../de/web/api/htmlformelement/elements/index.html | 46 + files/de/web/api/htmlformelement/index.html | 260 ++ .../api/htmlformelement/submit_event/index.html | 76 + files/de/web/api/htmlinputelement/index.html | 435 +++ .../de/web/api/htmlinputelement/select/index.html | 84 + .../api/htmlslotelement/assignednodes/index.html | 66 + files/de/web/api/htmlslotelement/index.html | 67 + .../api/htmltableelement/createcaption/index.html | 75 + files/de/web/api/htmltableelement/index.html | 132 + .../web/api/htmltableelement/insertrow/index.html | 122 + files/de/web/api/htmlunknownelement/index.html | 56 + files/de/web/api/index.html | 14 + .../index.html | 131 + .../grundkonzepte_hinter_indexeddb/index.html | 194 ++ files/de/web/api/indexeddb_api/index.html | 252 ++ .../indexeddb_api/indexeddb_verwenden/index.html | 1180 ++++++++ files/de/web/api/keyboardevent/altkey/index.html | 118 + .../api/keyboardevent/getmodifierstate/index.html | 247 ++ files/de/web/api/keyboardevent/index.html | 458 +++ files/de/web/api/keyboardevent/keycode/index.html | 3185 ++++++++++++++++++++ .../de/web/api/l10n.language.direction/index.html | 63 + files/de/web/api/linkstyle/index.html | 56 + files/de/web/api/messageevent/index.html | 205 ++ files/de/web/api/mouseevent/index.html | 323 ++ files/de/web/api/mozmobileconnection/index.html | 134 + .../selectnetworkautomatically/index.html | 57 + files/de/web/api/mutationobserver/index.html | 287 ++ files/de/web/api/navigator/index.html | 122 + .../navigator/registerprotocolhandler/index.html | 170 ++ .../webbasierte_protokoll-handler/index.html | 127 + files/de/web/api/navigator/sendbeacon/index.html | 144 + files/de/web/api/navigator/vibrate/index.html | 107 + files/de/web/api/navigatoronline/index.html | 127 + files/de/web/api/navigatoronline/online/index.html | 190 ++ .../online_and_offline_events/index.html | 120 + files/de/web/api/node/appendchild/index.html | 144 + files/de/web/api/node/childnodes/index.html | 70 + files/de/web/api/node/clonenode/index.html | 135 + files/de/web/api/node/firstchild/index.html | 62 + files/de/web/api/node/haschildnodes/index.html | 120 + files/de/web/api/node/index.html | 365 +++ files/de/web/api/node/innertext/index.html | 90 + files/de/web/api/node/lastchild/index.html | 41 + files/de/web/api/node/nextsibling/index.html | 60 + files/de/web/api/node/nodevalue/index.html | 88 + files/de/web/api/node/normalize/index.html | 49 + files/de/web/api/node/parentnode/index.html | 79 + files/de/web/api/node/previoussibling/index.html | 69 + files/de/web/api/node/removechild/index.html | 82 + files/de/web/api/node/replacechild/index.html | 61 + files/de/web/api/node/setuserdata/index.html | 121 + files/de/web/api/node/textcontent/index.html | 69 + files/de/web/api/notification/index.html | 265 ++ .../de/web/api/notification/permission/index.html | 187 ++ files/de/web/api/page_visibility_api/index.html | 189 ++ files/de/web/api/performance/index.html | 135 + files/de/web/api/performance/now/index.html | 164 + files/de/web/api/push_api/index.html | 180 ++ files/de/web/api/pushmanager/index.html | 161 + files/de/web/api/pushmanager/subscribe/index.html | 143 + files/de/web/api/range/index.html | 254 ++ files/de/web/api/range/range/index.html | 95 + files/de/web/api/readablestream/index.html | 101 + files/de/web/api/renderingcontext/index.html | 41 + files/de/web/api/response/index.html | 120 + files/de/web/api/response/response/index.html | 75 + files/de/web/api/rtcicecandidate/index.html | 121 + files/de/web/api/rtcpeerconnection/index.html | 379 +++ .../web/api/rtcrtptransceiver/direction/index.html | 82 + files/de/web/api/rtcrtptransceiver/index.html | 85 + files/de/web/api/service_worker_api/index.html | 280 ++ .../using_service_workers/index.html | 507 ++++ files/de/web/api/serviceworker/index.html | 103 + files/de/web/api/serviceworkercontainer/index.html | 158 + .../api/serviceworkercontainer/register/index.html | 122 + files/de/web/api/sharedworker/index.html | 117 + files/de/web/api/speechsynthesis/index.html | 134 + files/de/web/api/storage/clear/index.html | 61 + files/de/web/api/storage/getitem/index.html | 78 + files/de/web/api/storage/index.html | 161 + files/de/web/api/storage/key/index.html | 75 + files/de/web/api/storage/length/index.html | 63 + files/de/web/api/storage/removeitem/index.html | 68 + files/de/web/api/storage/setitem/index.html | 146 + files/de/web/api/transferable/index.html | 122 + files/de/web/api/url/createobjecturl/index.html | 139 + files/de/web/api/url/index.html | 222 ++ files/de/web/api/url/protocol/index.html | 61 + files/de/web/api/urlsearchparams/index.html | 211 ++ files/de/web/api/usvstring/index.html | 42 + files/de/web/api/vollbild_api/index.html | 305 ++ files/de/web/api/web_animations_api/index.html | 99 + files/de/web/api/web_storage_api/index.html | 142 + files/de/web/api/web_workers_api/index.html | 226 ++ files/de/web/api/webgl_api/index.html | 258 ++ .../3d-objekte_mit_webgl_erstellen/index.html | 126 + .../animierte_texturen_in_webgl/index.html | 89 + .../tutorial/beleuchtung_in_webgl/index.html | 172 ++ .../einf\303\274hrung_in_webgl/index.html" | 73 + .../index.html" | 97 + .../index.html" | 238 ++ files/de/web/api/webgl_api/tutorial/index.html | 40 + .../objekte_mit_webgl_animieren/index.html | 118 + .../texturen_in_webgl_verwenden/index.html | 159 + files/de/web/api/webglactiveinfo/index.html | 129 + files/de/web/api/webglprogram/index.html | 166 + .../api/webglrenderingcontext/canvas/index.html | 74 + .../getactiveattrib/index.html | 115 + .../getattriblocation/index.html | 65 + files/de/web/api/webglrenderingcontext/index.html | 441 +++ files/de/web/api/websocket/binarytype/index.html | 56 + files/de/web/api/websocket/close/index.html | 64 + files/de/web/api/websocket/extensions/index.html | 49 + files/de/web/api/websocket/index.html | 314 ++ files/de/web/api/websocket/onclose/index.html | 45 + files/de/web/api/websocket/protocol/index.html | 51 + files/de/web/api/websocket/readystate/index.html | 77 + files/de/web/api/websocket/url/index.html | 47 + files/de/web/api/webxr_device_api/index.html | 298 ++ files/de/web/api/window/alert/index.html | 72 + .../de/web/api/window/applicationcache/index.html | 33 + .../web/api/window/cancelanimationframe/index.html | 72 + files/de/web/api/window/close/index.html | 78 + files/de/web/api/window/confirm/index.html | 73 + files/de/web/api/window/console/index.html | 56 + files/de/web/api/window/dump/index.html | 42 + files/de/web/api/window/history/index.html | 56 + files/de/web/api/window/index.html | 384 +++ files/de/web/api/window/length/index.html | 51 + files/de/web/api/window/localstorage/index.html | 81 + files/de/web/api/window/name/index.html | 57 + files/de/web/api/window/navigator/index.html | 98 + files/de/web/api/window/ondevicemotion/index.html | 56 + files/de/web/api/window/opendialog/index.html | 90 + files/de/web/api/window/opener/index.html | 28 + files/de/web/api/window/performance/index.html | 96 + files/de/web/api/window/print/index.html | 50 + files/de/web/api/window/prompt/index.html | 79 + files/de/web/api/window/screenx/index.html | 98 + files/de/web/api/window/scroll/index.html | 56 + files/de/web/api/window/scrollto/index.html | 75 + files/de/web/api/window/sessionstorage/index.html | 90 + files/de/web/api/window/stop/index.html | 38 + files/de/web/api/windowbase64/btoa/index.html | 145 + files/de/web/api/windowbase64/index.html | 120 + files/de/web/api/windoweventhandlers/index.html | 189 ++ .../windoweventhandlers/onafterprint/index.html | 93 + .../windoweventhandlers/onhashchange/index.html | 162 + .../api/windoweventhandlers/onpopstate/index.html | 57 + files/de/web/api/windowtimers/index.html | 124 + .../de/web/api/windowtimers/settimeout/index.html | 329 ++ files/de/web/api/worker/index.html | 191 ++ files/de/web/api/xmlhttprequest/index.html | 710 +++++ .../xmlhttprequest/using_xmlhttprequest/index.html | 789 +++++ 294 files changed, 44794 insertions(+) create mode 100644 files/de/web/api/aescbcparams/index.html create mode 100644 files/de/web/api/animationevent/index.html create mode 100644 files/de/web/api/audiocontext/decodeaudiodata/index.html create mode 100644 files/de/web/api/audiocontext/index.html create mode 100644 files/de/web/api/audiodestinationnode/index.html create mode 100644 files/de/web/api/audionode/index.html create mode 100644 files/de/web/api/audiotrack/index.html create mode 100644 files/de/web/api/battery_status_api/index.html create mode 100644 files/de/web/api/blob/index.html create mode 100644 files/de/web/api/body/arraybuffer/index.html create mode 100644 files/de/web/api/body/blob/index.html create mode 100644 files/de/web/api/body/body/index.html create mode 100644 files/de/web/api/body/bodyused/index.html create mode 100644 files/de/web/api/body/formdata/index.html create mode 100644 files/de/web/api/body/index.html create mode 100644 files/de/web/api/body/json/index.html create mode 100644 files/de/web/api/body/text/index.html create mode 100644 files/de/web/api/cache/add/index.html create mode 100644 files/de/web/api/cache/addall/index.html create mode 100644 files/de/web/api/cache/index.html create mode 100644 files/de/web/api/canvasrenderingcontext2d/canvas/index.html create mode 100644 files/de/web/api/canvasrenderingcontext2d/fillrect/index.html create mode 100644 files/de/web/api/canvasrenderingcontext2d/getimagedata/index.html create mode 100644 files/de/web/api/canvasrenderingcontext2d/index.html create mode 100644 files/de/web/api/canvasrenderingcontext2d/ispointinpath/index.html create mode 100644 files/de/web/api/canvasrenderingcontext2d/scale/index.html create mode 100644 files/de/web/api/canvasrenderingcontext2d/setlinedash/index.html create mode 100644 files/de/web/api/canvasrenderingcontext2d/textalign/index.html create mode 100644 files/de/web/api/childnode/index.html create mode 100644 files/de/web/api/childnode/remove/index.html create mode 100644 files/de/web/api/console/assert/index.html create mode 100644 files/de/web/api/console/clear/index.html create mode 100644 files/de/web/api/console/count/index.html create mode 100644 files/de/web/api/console/debug/index.html create mode 100644 files/de/web/api/console/dir/index.html create mode 100644 files/de/web/api/console/index.html create mode 100644 files/de/web/api/console/log/index.html create mode 100644 files/de/web/api/console/table/index.html create mode 100644 files/de/web/api/console/time/index.html create mode 100644 files/de/web/api/console/timeend/index.html create mode 100644 files/de/web/api/console/warn/index.html create mode 100644 files/de/web/api/crypto/index.html create mode 100644 files/de/web/api/css/escape/index.html create mode 100644 files/de/web/api/css/index.html create mode 100644 files/de/web/api/css_painting_api/guide/index.html create mode 100644 files/de/web/api/css_painting_api/index.html create mode 100644 files/de/web/api/cssmediarule/index.html create mode 100644 files/de/web/api/csspagerule/index.html create mode 100644 files/de/web/api/cssrule/csstext/index.html create mode 100644 files/de/web/api/cssrule/index.html create mode 100644 files/de/web/api/customelementregistry/define/index.html create mode 100644 files/de/web/api/customelementregistry/index.html create mode 100644 files/de/web/api/dedicatedworkerglobalscope/index.html create mode 100644 files/de/web/api/dedicatedworkerglobalscope/message_event/index.html create mode 100644 files/de/web/api/document/adoptnode/index.html create mode 100644 files/de/web/api/document/alinkcolor/index.html create mode 100644 files/de/web/api/document/body/index.html create mode 100644 files/de/web/api/document/createattribute/index.html create mode 100644 files/de/web/api/document/createdocumentfragment/index.html create mode 100644 files/de/web/api/document/createelement/index.html create mode 100644 files/de/web/api/document/createelementns/index.html create mode 100644 files/de/web/api/document/createtextnode/index.html create mode 100644 files/de/web/api/document/createtreewalker/index.html create mode 100644 files/de/web/api/document/dir/index.html create mode 100644 files/de/web/api/document/document/index.html create mode 100644 files/de/web/api/document/documentelement/index.html create mode 100644 files/de/web/api/document/fullscreenchange_event/index.html create mode 100644 files/de/web/api/document/getelementbyid/index.html create mode 100644 files/de/web/api/document/getelementsbyclassname/index.html create mode 100644 files/de/web/api/document/head/index.html create mode 100644 files/de/web/api/document/importnode/index.html create mode 100644 files/de/web/api/document/index.html create mode 100644 files/de/web/api/document/queryselector/index.html create mode 100644 files/de/web/api/document/queryselectorall/index.html create mode 100644 files/de/web/api/document/readystate/index.html create mode 100644 files/de/web/api/document/referrer/index.html create mode 100644 files/de/web/api/document/registerelement/index.html create mode 100644 files/de/web/api/document/title/index.html create mode 100644 files/de/web/api/document/url/index.html create mode 100644 files/de/web/api/document/width/index.html create mode 100644 files/de/web/api/document/write/index.html create mode 100644 files/de/web/api/document/writeln/index.html create mode 100644 files/de/web/api/documentfragment/index.html create mode 100644 files/de/web/api/domerror/index.html create mode 100644 files/de/web/api/domparser/index.html create mode 100644 files/de/web/api/domstring/index.html create mode 100644 files/de/web/api/domtokenlist/add/index.html create mode 100644 files/de/web/api/domtokenlist/index.html create mode 100644 files/de/web/api/dragevent/index.html create mode 100644 files/de/web/api/element/classlist/index.html create mode 100644 files/de/web/api/element/classname/index.html create mode 100644 files/de/web/api/element/getboundingclientrect/index.html create mode 100644 files/de/web/api/element/hasattribute/index.html create mode 100644 files/de/web/api/element/index.html create mode 100644 files/de/web/api/element/innerhtml/index.html create mode 100644 files/de/web/api/element/insertadjacenthtml/index.html create mode 100644 files/de/web/api/element/queryselector/index.html create mode 100644 files/de/web/api/element/queryselectorall/index.html create mode 100644 files/de/web/api/element/removeattribute/index.html create mode 100644 files/de/web/api/element/requestfullscreen/index.html create mode 100644 files/de/web/api/element/scrollintoview/index.html create mode 100644 files/de/web/api/element/scrollleft/index.html create mode 100644 files/de/web/api/element/scrollwidth/index.html create mode 100644 files/de/web/api/element/setattribute/index.html create mode 100644 files/de/web/api/event/bubbles/index.html create mode 100644 files/de/web/api/event/event/index.html create mode 100644 files/de/web/api/event/index.html create mode 100644 files/de/web/api/eventlistener/index.html create mode 100644 files/de/web/api/eventsource/index.html create mode 100644 files/de/web/api/eventtarget/index.html create mode 100644 files/de/web/api/federatedcredential/index.html create mode 100644 files/de/web/api/fetch_api/index.html create mode 100644 files/de/web/api/file/filename/index.html create mode 100644 files/de/web/api/file/filesize/index.html create mode 100644 files/de/web/api/file/getastext/index.html create mode 100644 files/de/web/api/file/index.html create mode 100644 files/de/web/api/file/name/index.html create mode 100644 files/de/web/api/file/typ/index.html create mode 100644 files/de/web/api/file/zugriff_auf_dateien_von_webapplikationen/index.html create mode 100644 files/de/web/api/filereader/index.html create mode 100644 files/de/web/api/filereader/onload/index.html create mode 100644 files/de/web/api/formdata/formdata/index.html create mode 100644 files/de/web/api/formdata/get/index.html create mode 100644 files/de/web/api/formdata/getall/index.html create mode 100644 files/de/web/api/formdata/index.html create mode 100644 files/de/web/api/fullscreenoptions/index.html create mode 100644 files/de/web/api/gainnode/index.html create mode 100644 files/de/web/api/gamepad_api/index.html create mode 100644 files/de/web/api/geolocation/getcurrentposition/index.html create mode 100644 files/de/web/api/geolocation/index.html create mode 100644 files/de/web/api/globaleventhandlers/index.html create mode 100644 files/de/web/api/globaleventhandlers/onclick/index.html create mode 100644 files/de/web/api/globaleventhandlers/onload/index.html create mode 100644 files/de/web/api/globaleventhandlers/onresize/index.html create mode 100644 files/de/web/api/htmlcanvaselement/index.html create mode 100644 files/de/web/api/htmlcanvaselement/todataurl/index.html create mode 100644 files/de/web/api/htmlcanvaselement/webglcontextcreationerror_event/index.html create mode 100644 files/de/web/api/htmlcanvaselement/webglcontextlost_event/index.html create mode 100644 files/de/web/api/htmlcanvaselement/webglcontextrestored_event/index.html create mode 100644 files/de/web/api/htmlcollection/index.html create mode 100644 files/de/web/api/htmlformelement/elements/index.html create mode 100644 files/de/web/api/htmlformelement/index.html create mode 100644 files/de/web/api/htmlformelement/submit_event/index.html create mode 100644 files/de/web/api/htmlinputelement/index.html create mode 100644 files/de/web/api/htmlinputelement/select/index.html create mode 100644 files/de/web/api/htmlslotelement/assignednodes/index.html create mode 100644 files/de/web/api/htmlslotelement/index.html create mode 100644 files/de/web/api/htmltableelement/createcaption/index.html create mode 100644 files/de/web/api/htmltableelement/index.html create mode 100644 files/de/web/api/htmltableelement/insertrow/index.html create mode 100644 files/de/web/api/htmlunknownelement/index.html create mode 100644 files/de/web/api/index.html create mode 100644 files/de/web/api/indexeddb_api/browser_storage_limits_and_eviction_criteria/index.html create mode 100644 files/de/web/api/indexeddb_api/grundkonzepte_hinter_indexeddb/index.html create mode 100644 files/de/web/api/indexeddb_api/index.html create mode 100644 files/de/web/api/indexeddb_api/indexeddb_verwenden/index.html create mode 100644 files/de/web/api/keyboardevent/altkey/index.html create mode 100644 files/de/web/api/keyboardevent/getmodifierstate/index.html create mode 100644 files/de/web/api/keyboardevent/index.html create mode 100644 files/de/web/api/keyboardevent/keycode/index.html create mode 100644 files/de/web/api/l10n.language.direction/index.html create mode 100644 files/de/web/api/linkstyle/index.html create mode 100644 files/de/web/api/messageevent/index.html create mode 100644 files/de/web/api/mouseevent/index.html create mode 100644 files/de/web/api/mozmobileconnection/index.html create mode 100644 files/de/web/api/mozmobileconnection/selectnetworkautomatically/index.html create mode 100644 files/de/web/api/mutationobserver/index.html create mode 100644 files/de/web/api/navigator/index.html create mode 100644 files/de/web/api/navigator/registerprotocolhandler/index.html create mode 100644 files/de/web/api/navigator/registerprotocolhandler/webbasierte_protokoll-handler/index.html create mode 100644 files/de/web/api/navigator/sendbeacon/index.html create mode 100644 files/de/web/api/navigator/vibrate/index.html create mode 100644 files/de/web/api/navigatoronline/index.html create mode 100644 files/de/web/api/navigatoronline/online/index.html create mode 100644 files/de/web/api/navigatoronline/online_and_offline_events/index.html create mode 100644 files/de/web/api/node/appendchild/index.html create mode 100644 files/de/web/api/node/childnodes/index.html create mode 100644 files/de/web/api/node/clonenode/index.html create mode 100644 files/de/web/api/node/firstchild/index.html create mode 100644 files/de/web/api/node/haschildnodes/index.html create mode 100644 files/de/web/api/node/index.html create mode 100644 files/de/web/api/node/innertext/index.html create mode 100644 files/de/web/api/node/lastchild/index.html create mode 100644 files/de/web/api/node/nextsibling/index.html create mode 100644 files/de/web/api/node/nodevalue/index.html create mode 100644 files/de/web/api/node/normalize/index.html create mode 100644 files/de/web/api/node/parentnode/index.html create mode 100644 files/de/web/api/node/previoussibling/index.html create mode 100644 files/de/web/api/node/removechild/index.html create mode 100644 files/de/web/api/node/replacechild/index.html create mode 100644 files/de/web/api/node/setuserdata/index.html create mode 100644 files/de/web/api/node/textcontent/index.html create mode 100644 files/de/web/api/notification/index.html create mode 100644 files/de/web/api/notification/permission/index.html create mode 100644 files/de/web/api/page_visibility_api/index.html create mode 100644 files/de/web/api/performance/index.html create mode 100644 files/de/web/api/performance/now/index.html create mode 100644 files/de/web/api/push_api/index.html create mode 100644 files/de/web/api/pushmanager/index.html create mode 100644 files/de/web/api/pushmanager/subscribe/index.html create mode 100644 files/de/web/api/range/index.html create mode 100644 files/de/web/api/range/range/index.html create mode 100644 files/de/web/api/readablestream/index.html create mode 100644 files/de/web/api/renderingcontext/index.html create mode 100644 files/de/web/api/response/index.html create mode 100644 files/de/web/api/response/response/index.html create mode 100644 files/de/web/api/rtcicecandidate/index.html create mode 100644 files/de/web/api/rtcpeerconnection/index.html create mode 100644 files/de/web/api/rtcrtptransceiver/direction/index.html create mode 100644 files/de/web/api/rtcrtptransceiver/index.html create mode 100644 files/de/web/api/service_worker_api/index.html create mode 100644 files/de/web/api/service_worker_api/using_service_workers/index.html create mode 100644 files/de/web/api/serviceworker/index.html create mode 100644 files/de/web/api/serviceworkercontainer/index.html create mode 100644 files/de/web/api/serviceworkercontainer/register/index.html create mode 100644 files/de/web/api/sharedworker/index.html create mode 100644 files/de/web/api/speechsynthesis/index.html create mode 100644 files/de/web/api/storage/clear/index.html create mode 100644 files/de/web/api/storage/getitem/index.html create mode 100644 files/de/web/api/storage/index.html create mode 100644 files/de/web/api/storage/key/index.html create mode 100644 files/de/web/api/storage/length/index.html create mode 100644 files/de/web/api/storage/removeitem/index.html create mode 100644 files/de/web/api/storage/setitem/index.html create mode 100644 files/de/web/api/transferable/index.html create mode 100644 files/de/web/api/url/createobjecturl/index.html create mode 100644 files/de/web/api/url/index.html create mode 100644 files/de/web/api/url/protocol/index.html create mode 100644 files/de/web/api/urlsearchparams/index.html create mode 100644 files/de/web/api/usvstring/index.html create mode 100644 files/de/web/api/vollbild_api/index.html create mode 100644 files/de/web/api/web_animations_api/index.html create mode 100644 files/de/web/api/web_storage_api/index.html create mode 100644 files/de/web/api/web_workers_api/index.html create mode 100644 files/de/web/api/webgl_api/index.html create mode 100644 files/de/web/api/webgl_api/tutorial/3d-objekte_mit_webgl_erstellen/index.html create mode 100644 files/de/web/api/webgl_api/tutorial/animierte_texturen_in_webgl/index.html create mode 100644 files/de/web/api/webgl_api/tutorial/beleuchtung_in_webgl/index.html create mode 100644 "files/de/web/api/webgl_api/tutorial/einf\303\274hrung_in_webgl/index.html" create mode 100644 "files/de/web/api/webgl_api/tutorial/farben_mittels_shader_in_einen_webgl-kontext_hinzuf\303\274gen/index.html" create mode 100644 "files/de/web/api/webgl_api/tutorial/hinzuf\303\274gen_von_2d_inhalten_in_einen_webgl-kontext/index.html" create mode 100644 files/de/web/api/webgl_api/tutorial/index.html create mode 100644 files/de/web/api/webgl_api/tutorial/objekte_mit_webgl_animieren/index.html create mode 100644 files/de/web/api/webgl_api/tutorial/texturen_in_webgl_verwenden/index.html create mode 100644 files/de/web/api/webglactiveinfo/index.html create mode 100644 files/de/web/api/webglprogram/index.html create mode 100644 files/de/web/api/webglrenderingcontext/canvas/index.html create mode 100644 files/de/web/api/webglrenderingcontext/getactiveattrib/index.html create mode 100644 files/de/web/api/webglrenderingcontext/getattriblocation/index.html create mode 100644 files/de/web/api/webglrenderingcontext/index.html create mode 100644 files/de/web/api/websocket/binarytype/index.html create mode 100644 files/de/web/api/websocket/close/index.html create mode 100644 files/de/web/api/websocket/extensions/index.html create mode 100644 files/de/web/api/websocket/index.html create mode 100644 files/de/web/api/websocket/onclose/index.html create mode 100644 files/de/web/api/websocket/protocol/index.html create mode 100644 files/de/web/api/websocket/readystate/index.html create mode 100644 files/de/web/api/websocket/url/index.html create mode 100644 files/de/web/api/webxr_device_api/index.html create mode 100644 files/de/web/api/window/alert/index.html create mode 100644 files/de/web/api/window/applicationcache/index.html create mode 100644 files/de/web/api/window/cancelanimationframe/index.html create mode 100644 files/de/web/api/window/close/index.html create mode 100644 files/de/web/api/window/confirm/index.html create mode 100644 files/de/web/api/window/console/index.html create mode 100644 files/de/web/api/window/dump/index.html create mode 100644 files/de/web/api/window/history/index.html create mode 100644 files/de/web/api/window/index.html create mode 100644 files/de/web/api/window/length/index.html create mode 100644 files/de/web/api/window/localstorage/index.html create mode 100644 files/de/web/api/window/name/index.html create mode 100644 files/de/web/api/window/navigator/index.html create mode 100644 files/de/web/api/window/ondevicemotion/index.html create mode 100644 files/de/web/api/window/opendialog/index.html create mode 100644 files/de/web/api/window/opener/index.html create mode 100644 files/de/web/api/window/performance/index.html create mode 100644 files/de/web/api/window/print/index.html create mode 100644 files/de/web/api/window/prompt/index.html create mode 100644 files/de/web/api/window/screenx/index.html create mode 100644 files/de/web/api/window/scroll/index.html create mode 100644 files/de/web/api/window/scrollto/index.html create mode 100644 files/de/web/api/window/sessionstorage/index.html create mode 100644 files/de/web/api/window/stop/index.html create mode 100644 files/de/web/api/windowbase64/btoa/index.html create mode 100644 files/de/web/api/windowbase64/index.html create mode 100644 files/de/web/api/windoweventhandlers/index.html create mode 100644 files/de/web/api/windoweventhandlers/onafterprint/index.html create mode 100644 files/de/web/api/windoweventhandlers/onhashchange/index.html create mode 100644 files/de/web/api/windoweventhandlers/onpopstate/index.html create mode 100644 files/de/web/api/windowtimers/index.html create mode 100644 files/de/web/api/windowtimers/settimeout/index.html create mode 100644 files/de/web/api/worker/index.html create mode 100644 files/de/web/api/xmlhttprequest/index.html create mode 100644 files/de/web/api/xmlhttprequest/using_xmlhttprequest/index.html (limited to 'files/de/web/api') diff --git a/files/de/web/api/aescbcparams/index.html b/files/de/web/api/aescbcparams/index.html new file mode 100644 index 0000000000..65c2effd7b --- /dev/null +++ b/files/de/web/api/aescbcparams/index.html @@ -0,0 +1,52 @@ +--- +title: AesCbcParams +slug: Web/API/AesCbcParams +translation_of: Web/API/AesCbcParams +--- +
{{ APIRef("Web Crypto API") }}
+ +

Das AesCbcParams Verzeichnis (dictionary) der Web Crypto API wird als algorithm Parameter an die Funktionen {{domxref("SubtleCrypto.encrypt()")}}, {{domxref("SubtleCrypto.decrypt()")}}, {{domxref("SubtleCrypto.wrapKey()")}} und {{domxref("SubtleCrypto.unwrapKey()")}} übergeben, wenn der Algorithmus AES-CBC verwendet wird.

+ +

Eigenschaften

+ +
+
name
+
A {{domxref("DOMString")}}. Der Wert sollte auf AES-CBC gesetzt werden.
+
iv
+
Ein {{domxref("BufferSource")}}. Der Initialisierungsvektor. Er muss 16 Bytes lang sein und sollte unvorhersehbar und am besten kryptografisch zufällig sein. Er muss aber nicht geheim sein, er kann unverschlüsselt mit dem Kryptogram übertragen werden.
+
+ +

Beispiele

+ +

Siehe Beispiele für {{domxref("SubtleCrypto.encrypt()")}} und {{domxref("SubtleCrypto.decrypt()")}}.

+ +

Spezifikationen

+ + + + + + + + + + + + + + +
SpezifikationStatusKommentar
{{ SpecName('Web Crypto API', '#dfn-AesCbcParams', 'SubtleCrypto.AesCbcParams') }}{{ Spec2('Web Crypto API') }}
+ +

Browser Kompatibilität

+ +

Browser mit Unterstützung für den "AES-CBC" Algorithmus werden die Methoden {{domxref("SubtleCrypto.encrypt()")}}, {{domxref("SubtleCrypto.decrypt()")}}, {{domxref("SubtleCrypto.wrapKey()")}} und {{domxref("SubtleCrypto.unwrapKey()")}} für diesen Typ unterstützen.

+ +

Siehe auch

+ + diff --git a/files/de/web/api/animationevent/index.html b/files/de/web/api/animationevent/index.html new file mode 100644 index 0000000000..7bd808e0ca --- /dev/null +++ b/files/de/web/api/animationevent/index.html @@ -0,0 +1,190 @@ +--- +title: AnimationEvent +slug: Web/API/AnimationEvent +tags: + - API + - Experimental + - Expérimental(2) + - Interface + - NeedsTranslation + - Reference + - Référence(2) + - TopicStub + - Web Animations +translation_of: Web/API/AnimationEvent +--- +

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

+ +

The AnimationEvent interface represents events providing information related to animations.

+ +

{{InheritanceDiagram}}

+ +

Properties

+ +

Also inherits properties from its parent {{domxref("Event")}}.

+ +
+
{{domxref("AnimationEvent.animationName")}} {{readonlyInline}}
+
Is a {{domxref("DOMString")}} containing the value of the {{cssxref("animation-name")}} CSS property associated with the transition.
+
{{domxref("AnimationEvent.elapsedTime")}} {{readonlyInline}}
+
Is a float giving the amount of time the animation has been running, in seconds, when this event fired, excluding any time the animation was paused. For an "animationstart" event, elapsedTime is 0.0 unless there was a negative value for {{cssxref("animation-delay")}}, in which case the event will be fired with elapsedTime containing  (-1 * delay).
+
{{domxref("AnimationEvent.pseudoElement")}} {{readonlyInline}}
+
Is a {{domxref("DOMString")}}, starting with '::', containing the name of the pseudo-element the animation runs on. If the animation doesn't run on a pseudo-element but on the element, an empty string: ''.
+
+ +

Constructor

+ +
+
{{domxref("AnimationEvent.AnimationEvent", "AnimationEvent()")}}
+
Creates an AnimationEvent event with the given parameters.
+
+ +

Methods

+ +

Also inherits methods from its parent {{domxref("Event")}}.

+ +
+
{{domxref("AnimationEvent.initAnimationEvent()")}} {{non-standard_inline}}{{deprecated_inline}}
+
Initializes a AnimationEvent created using the deprecated {{domxref("Document.createEvent()", "Document.createEvent(\"AnimationEvent\")")}} method.
+
+ +

Specifications

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

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (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}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox 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}}
+
+ +

See also

+ + diff --git a/files/de/web/api/audiocontext/decodeaudiodata/index.html b/files/de/web/api/audiocontext/decodeaudiodata/index.html new file mode 100644 index 0000000000..32cfda28eb --- /dev/null +++ b/files/de/web/api/audiocontext/decodeaudiodata/index.html @@ -0,0 +1,218 @@ +--- +title: AudioContext.decodeAudioData() +slug: Web/API/AudioContext/decodeAudioData +translation_of: Web/API/BaseAudioContext/decodeAudioData +--- +

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

+ +
+

Die Methode decodeAudioData() im Interface {{ domxref("AudioContext") }} wird dazu benutzt um in einem {{ domxref("ArrayBuffer")}} enthaltene Audiodaten asynchron zu dekodieren. Im Normalfall wird der ArrayBuffer mit der  {{domxref("XMLHttpRequest")}} response Eigenschaft befüllt, nachdem der responseType auf arraybuffer gesetzt wurde. Der dekodierte AudioBuffer wird auf die Samplerate des AudioContextes angepasst und anschließend an ein Callback oder Promise weitergegeben.

+
+ +

Dies ist die bevorzugte Methode im eine Audioquelle für die Web Audio API aus einem Audiotrack zu generieren.

+ +

Syntax

+ +

Alte Callbacksyntax:

+ +
audioCtx.decodeAudioData(audioData, function(decodedData) {
+  // use the dec​oded data here
+});
+ +

Neue Promise basierte Syntax:

+ +
audioCtx.decodeAudioData(audioData).then(function(decodedData) {
+  // use the decoded data here
+});
+ +

Beispiel

+ +

In diesem Abschnitt wird zuerst die ältere Callback basierte Syntax und anschließend die neue Promise basierte Syntax behandelt.

+ +

Ältere Callbacksyntax

+ +

In diesem Beispiel nutzt die getData() Funktion XHR um einen Audiotrack zu laden, indem sie die responseType Eigenschaft setzt um einen ArrayBuffer als Antwort zu erhalten, welcher anschließend in der audioData variable gespeichert wird. Dieser Buffer wird nun an die decodeAudioData() Funktion übergeben; Das success Callback nutzt die erfolgreich dekodierten PCM Daten, erstellt einen {{ domxref("AudioBufferSourceNode") }} mit Hilfe von {{ domxref("AudioContext.createBufferSource()") }}, verbindet diese Quelle mit {{domxref("AudioContext.destination") }} und setzt den Schleifenmodus.

+ +

Die Buttons in diesem Beispiel rufen lediglich getData() um die Daten zu laden und die Wiedergabe zu starten, sowie stop() um die Wiedergabe anzuhalten auf. Wenn die stop() Methode der Quelle aufgerufen wird die Quelle geleert.

+ +
+

Note: You can run the example live (or view the source.)

+
+ +
// Variablen definieren
+
+var audioCtx = new (window.AudioContext || window.webkitAudioContext)();
+var source;
+
+var pre = document.querySelector('pre');
+var myScript = document.querySelector('script');
+var play = document.querySelector('.play');
+var stop = document.querySelector('.stop');
+
+// Benutzt XHR um einen Track zu laden und
+// decodeAudioData um diesen zu dekodieren und in einen Buffer zu kopieren.
+// Anschließend wird der Buffer in eine Quelle kopiert.
+
+function getData() {
+  source = audioCtx.createBufferSource();
+  var request = new XMLHttpRequest();
+
+  request.open('GET', 'viper.ogg', true);
+
+  request.responseType = 'arraybuffer';
+
+
+  request.onload = function() {
+    var audioData = request.response;
+
+    audioCtx.decodeAudioData(audioData, function(buffer) {
+        source.buffer = buffer;
+
+        source.connect(audioCtx.destination);
+        source.loop = true;
+      },
+
+      function(e){"Error with decoding audio data" + e.err});
+
+  }
+
+  request.send();
+}
+
+// Buttons setzen um Wiedergabe zu starten und stoppen
+
+play.onclick = function() {
+  getData();
+  source.start(0);
+  play.setAttribute('disabled', 'disabled');
+}
+
+stop.onclick = function() {
+  source.stop(0);
+  play.removeAttribute('disabled');
+}
+
+
+// Script ausgeben
+
+pre.innerHTML = myScript.innerHTML;
+ +

Neue Promise basierte Syntax

+ +
ctx.decodeAudioData(compressedBuffer).then(function(decodedData) {
+ // Die dekodierten PCM Daten können hier verwendet werden
+});
+ +

Parameter

+ +
+
ArrayBuffer
+
Ein ArrayBuffer der die zu dekodierenden Daten enthält. Dieser wird normalerweise durch einen {{domxref("XMLHttpRequest")}} befüllt nachdem der responseType auf arraybuffer gesetzt wurde.
+
DecodeSuccessCallback
+
Ein Callback das aufgerufen wird wenn die Dekodierung erfolgreich abgeschlossen wird. Der einzige Parameter der an diese Funktion übergeben wird stellt einen AudioBuffer dar, der die dekodierten Audiodaten enthält. Normalerweise wird dieser Buffer an einen {{domxref("AudioBufferSourceNode")}} übergeben, von wo er wiedergeben und verändert werden kann.
+
DecodeErrorCallback
+
Ein optionales Callback das bei einem Fehler während der Dekodierung aufgerufen wird.
+
+ +

Rückgabewerte

+ +

Ein {{domxref("AudioBuffer") }} der die dekodierten Audiodaten enthällt.

+ +

Spezifikationen

+ + + + + + + + + + + + + + +
SpezifikationStatusKommentar
{{SpecName('Web Audio API', '#widl-AudioContext-decodeAudioData-Promise-AudioBuffer--ArrayBuffer-audioData-DecodeSuccessCallback-successCallback-DecodeErrorCallback-errorCallback', 'decodeAudioData()')}}{{Spec2('Web Audio API')}} 
+ +

Browserunterstützung

+ +
{{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")}}
Promise-based syntax{{CompatChrome(49.0)}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatUnknown}}{{CompatVersionUnknown}}26.01.2{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatChrome(33.0)}}
Promise-based syntax{{CompatUnknown}}{{CompatChrome(49.0)}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatChrome(49.0)}}
+
+ +

Siehe auch

+ + diff --git a/files/de/web/api/audiocontext/index.html b/files/de/web/api/audiocontext/index.html new file mode 100644 index 0000000000..cc2c2db92e --- /dev/null +++ b/files/de/web/api/audiocontext/index.html @@ -0,0 +1,232 @@ +--- +title: AudioContext +slug: Web/API/AudioContext +translation_of: Web/API/AudioContext +--- +

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

+ +
+

Die AudioContext Schnittstelle bildet einen Audioverarbeitungsdiagramm, aus mehreren miteinander verbundenen Audiomodulen bestehend, ab. Bei jedem dieser Module handelt es sich um einen Knoten ({{domxref("AudioNode")}}). Ein AudioContext kontrolliert sowohl die Erstellung der einzelnen in ihm enthaltenen Knoten als auch den Prozess der Audioverarbeitung oder des Dekodierens. Als erster Schritt muss immer ein Audio Kontext angelegt werden, da sämtliche Funktionen innerhalb dieses Kontextes ausgeführt werden.

+
+ +

Ein AudioContext kann das Ziel von Events sein, aufgrund dessen unterstützt er auch die {{domxref("EventTarget")}} Schnittstelle.

+ +

Eigenschaften

+ +
+
{{domxref("AudioContext.currentTime")}} {{readonlyInline}}
+
Returns a double representing an ever-increasing hardware time in seconds used for scheduling. It starts at 0.
+
{{domxref("AudioContext.destination")}} {{readonlyInline}}
+
Returns an {{domxref("AudioDestinationNode")}} representing the final destination of all audio in the context. It can be thought of as the audio-rendering device.
+
{{domxref("AudioContext.listener")}} {{readonlyInline}}
+
Returns the {{domxref("AudioListener")}} object, used for 3D spatialization.
+
{{domxref("AudioContext.sampleRate")}} {{readonlyInline}}
+
Returns a float representing the sample rate (in samples per second) used by all nodes in this context. The sample-rate of an {{domxref("AudioContext")}} cannot be changed.
+
{{domxref("AudioContext.state")}} {{readonlyInline}}
+
Returns the current state of the AudioContext.
+
{{domxref("AudioContext.mozAudioChannelType")}} {{ non-standard_inline() }} {{readonlyInline}}
+
Used to return the audio channel that the sound playing in an {{domxref("AudioContext")}} will play in, on a Firefox OS device.
+
+ +

Event handlers

+ +
+
{{domxref("AudioContext.onstatechange")}}
+
An event handler that runs when an event of type {{event("statechange")}} has fired. This occurs when the AudioContext's state changes, due to the calling of one of the state change methods ({{domxref("AudioContext.suspend")}}, {{domxref("AudioContext.resume")}}, or {{domxref("AudioContext.close")}}.)
+
+ +

Methoden

+ +

Implementiert zusätzlich die Methoden der Schnittstelle {{domxref("EventTarget")}}.

+ +
+
{{domxref("AudioContext.close()")}}
+
Closes the audio context, releasing any system audio resources that it uses.
+
{{domxref("AudioContext.createBuffer()")}}
+
Creates a new, empty {{ domxref("AudioBuffer") }} object, which can then be populated by data and played via an {{ domxref("AudioBufferSourceNode") }}.
+
{{domxref("AudioContext.createBufferSource()")}}
+
Creates an {{domxref("AudioBufferSourceNode")}}, which can be used to play and manipulate audio data contained within an {{ domxref("AudioBuffer") }} object. {{ domxref("AudioBuffer") }}s are created using {{domxref("AudioContext.createBuffer")}} or returned by {{domxref("AudioContext.decodeAudioData")}} when it successfully decodes an audio track.
+
{{domxref("AudioContext.createMediaElementSource()")}}
+
Creates a {{domxref("MediaElementAudioSourceNode")}} associated with an {{domxref("HTMLMediaElement")}}. This can be used to play and manipulate audio from {{HTMLElement("video")}} or {{HTMLElement("audio")}} elements.
+
{{domxref("AudioContext.createMediaStreamSource()")}}
+
Creates a {{domxref("MediaStreamAudioSourceNode")}} associated with a {{domxref("MediaStream")}} representing an audio stream which may come from the local computer microphone or other sources.
+
{{domxref("AudioContext.createMediaStreamDestination()")}}
+
Creates a {{domxref("MediaStreamAudioDestinationNode")}} associated with a {{domxref("MediaStream")}} representing an audio stream which may be stored in a local file or sent to another computer.
+
{{domxref("AudioContext.createScriptProcessor()")}}
+
Creates a {{domxref("ScriptProcessorNode")}}, which can be used for direct audio processing via JavaScript.
+
{{domxref("AudioContext.createStereoPanner()")}}
+
Creates a {{domxref("StereoPannerNode")}}, which can be used to apply stereo panning to an audio source.
+
{{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()")}}
+
Creates a {{domxref("BiquadFilterNode")}}, which represents a second order filter configurable as several different common filter types: high-pass, low-pass, band-pass, etc.
+
{{domxref("AudioContext.createChannelMerger()")}}
+
Creates a {{domxref("ChannelMergerNode")}}, which is used to combine channels from multiple audio streams into a single audio stream.
+
{{domxref("AudioContext.createChannelSplitter()")}}
+
Creates a {{domxref("ChannelSplitterNode")}}, which is used to access the individual channels of an audio stream and process them separately.
+
{{domxref("AudioContext.createConvolver()")}}
+
Creates a {{domxref("ConvolverNode")}}, which can be used to apply convolution effects to your audio graph, for example a reverberation effect.
+
{{domxref("AudioContext.createDelay()")}}
+
Creates a {{domxref("DelayNode")}}, which is used to delay the incoming audio signal by a certain amount. This node is also useful to create feedback loops in a Web Audio API graph.
+
{{domxref("AudioContext.createDynamicsCompressor()")}}
+
Creates a {{domxref("DynamicsCompressorNode")}}, which can be used to apply acoustic compression to an audio signal.
+
{{domxref("AudioContext.createGain()")}}
+
Creates a {{domxref("GainNode")}}, which can be used to control the overall volume of the audio graph.
+
{{domxref("AudioContext.createOscillator()")}}
+
Creates an {{domxref("OscillatorNode")}}, a source representing a periodic waveform. It basically generates a tone.
+
{{domxref("AudioContext.createPanner()")}}
+
Creates a {{domxref("PannerNode")}}, which is used to spatialise an incoming audio stream in 3D space.
+
{{domxref("AudioContext.createPeriodicWave()")}}
+
Creates a {{domxref("PeriodicWave")}}, used to define a periodic waveform that can be used to determine the output of an {{ domxref("OscillatorNode") }}.
+
{{domxref("AudioContext.createWaveShaper()")}}
+
Creates a {{domxref("WaveShaperNode")}}, which is used to implement non-linear distortion effects.
+
{{domxref("AudioContext.createAudioWorker()")}}
+
Creates an {{domxref("AudioWorkerNode")}}, which can interact with a web worker thread to generate, process, or analyse audio directly. This was added to the spec on August 29 2014, and is not implemented in any browser yet.
+
{{domxref("AudioContext.decodeAudioData()")}}
+
Asynchronously decodes audio file data contained in an {{domxref("ArrayBuffer")}}. In this case, the ArrayBuffer is usually loaded from an {{domxref("XMLHttpRequest")}}'s response attribute after setting the responseType to arraybuffer. This method only works on complete files, not fragments of audio files.
+
{{domxref("AudioContext.resume()")}}
+
Resumes the progression of time in an audio context that has previously been suspended.
+
{{domxref("AudioContext.suspend()")}}
+
Suspends the progression of time in the audio context, temporarily halting audio hardware access and reducing CPU/battery usage in the process.
+
+ +

Obsolete Methoden

+ +
+
{{domxref("AudioContext.createJavaScriptNode()")}}
+
Creates a {{domxref("JavaScriptNode")}}, used for direct audio processing via JavaScript. This method is obsolete, and has been replaced by {{domxref("AudioContext.createScriptProcessor()")}}.
+
{{domxref("AudioContext.createWaveTable()")}}
+
Creates a {{domxref("WaveTableNode")}}, used to define a periodic waveform. This method is obsolete, and has been replaced by {{domxref("AudioContext.createPeriodicWave()")}}.
+
+ +

Beispiele

+ +

Grundsätzliche Deklarierung eines Audio Kontextes:

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

Browserunabhängige Variante:

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

Spezifikationen

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Audio API', '#the-audiocontext-interface', 'AudioContext')}}{{Spec2('Web Audio API')}} 
+ +

Browserkompatibilität

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

Siehe auch

+ + diff --git a/files/de/web/api/audiodestinationnode/index.html b/files/de/web/api/audiodestinationnode/index.html new file mode 100644 index 0000000000..4acda5845c --- /dev/null +++ b/files/de/web/api/audiodestinationnode/index.html @@ -0,0 +1,141 @@ +--- +title: AudioDestinationNode +slug: Web/API/AudioDestinationNode +translation_of: Web/API/AudioDestinationNode +--- +

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

+ +
+

Die AudioDestinationNode Schnittstelle repräsentiert das Ziel bzw. den Ausgang eines Audiographen in einem gegebenen Kontext — in der Regel die Lautsprecher. Es könnte aber auch ein Knoten (Node) sein, der Audiodaten in einem OfflineAudioContext aufzeichnet.

+
+ +

AudioDestinationNode hat einen Eingang und keinen Ausgang (denn er ist der Ausgang, kein weiterer Audio Node kann verlinkt werden). Die Anzahl der Kanäle des Eingangs muss zwischen null und dem Wert von maxChannelCount liegen, sonst wird eine Exception ausgelöst.

+ +

Der AudioDestinationNode eines gegebenen AudioContext kann über das {{domxref("AudioContext.destination")}} Attribut erzeugt bzw. empfangen werden.

+ + + + + + + + + + + + + + + + + + + + + + + + +
Anzahl Inputs1
Anzahl Outputs0
Kanalzählmethode"explicit"
Kanal Anzahl2
Kanal Interpretation"speakers"
+ +

Eigenschaften

+ +

erbt Eigenschaften von der Elternklasse, {{domxref("AudioNode")}}.

+ +
+
{{domxref("AudioDestinationNode.maxChannelCount")}}
+
Ist ein unsigned long der die maximale Kanalzahl definiert, die das physische Gerät bedienen kann.
+
+ +

Methoden

+ +

Keine spezifischen Methoden; erbt die Methoden der Elternklasse, {{domxref("AudioNode")}}.

+ +

Beispiel

+ +

Das Benutzen des AudioDestinationNode ist per Design einfach gehalten — es repräsentiert den Ausgang des physikalischen Geräts (Lautsprecher), so dass man dieses mit ein paar Zeilen Code mit einem Audiographen verbinden kann:

+ +
var audioCtx = new AudioContext();
+var source = audioCtx.createMediaElementSource(myMediaElement);
+source.connect(gainNode);
+gainNode.connect(audioCtx.destination);
+ +

Für ein kompletteres Beispiel, sehen Sie sich eines unserer MDN Web Audio Beispiele, wie den Voice-change-o-matic oder das Violent Theremin an.

+ +

Spezifikationen

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Audio API', '#the-audiodestinationnode-interface', 'AudioDestinationNode')}}{{Spec2('Web Audio API')}} 
+ +

Browser Kompatibilität

+ +
{{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")}}
+
+ +

See also

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

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

+ +

Ein AudioNode ist eine generische Schnittstelle um ein Signalverarbeitungsmodul wie z.B. ein HTML {{HTMLElement("audio")}} or {{HTMLElement("video")}} Element, ein {{domxref("OscillatorNode")}}, die Audio Destination, ein zwischengeschaltenes audio-verarbeitendes Modul wie z.B. einen {{domxref("BiquadFilterNode")}} oder {{domxref("ConvolverNode")}}), oder Lautstärkeregler (like {{domxref("GainNode")}}).

+ +

AudioNodes participating in an AudioContext create a audio routing graph.

+ +

Ein AudioNode hat Ein- und Ausgänge, jeweils mit einer gegebenen Anzahl an Kanälen. Einen AudioNode ohne Eingänge und mit einem oder mehreren Ausgängen nennt man source node (dt.: Quellknoten). Die Art der Signalverarbeitung in einem Audio Node variiert mit dessen Funktion. Der folgende Ablauf liegt jedoch immer zugrunde:  das Signal am Eingang wird eingelesen,  das Signal wird zu einem neuen Signal verarbeitet und an den Ausgang geleitet. In einigen Fällen, wir das Signal unverarbeitet durchgeschleust, so z.B. beim {{domxref("AnalyserNode")}}, wo das Resultat der Signalverarbeitung separat zugänglich ist.

+ +

Mehrere Nodes können zu einem Processing Graph (dt.:Verarbeitungs-Netz) verbunden werden. Ein solcher Graph befindet sich immer in genau einem {{domxref("AudioContext")}}. Signal- verarbeitende Nodes erben die Eigenschaften und Methoden von Audio Node, implementieren aber auch eigene Funktionalität. Weitere Informationen geben die Seiten der speziellen Audio Nodes,  die sie auf der Homepage der Web Audio API finden.

+ +
+

Hinweis: Ein AudioNode kann das Ziel von Events sein, und implementiert daher die {{domxref("EventTarget")}} Schnittstelle.

+
+ +

Properties

+ +
+
{{domxref("AudioNode.context")}} {{readonlyInline}}
+
Liefert den assoziierten {{domxref("AudioContext")}}, der den signalverarbeitenden Graphen (processing graph) enthält, in den der Node eingebunden ist.
+
+ +
+
{{domxref("AudioNode.numberOfInputs")}} {{readonlyInline}}
+
Liefert die Anzahl der Eingänge des Nodes. Source nodes (dt. Quellknoten) sind definiert als Nodes, deren numberOfInputs Eigenschaft einen Wert von aufweist.
+
+ +
+
{{domxref("AudioNode.numberOfOutputs")}} {{readonlyInline}}
+
Liefert die Anzahl der Ausgänge des Nodes. Destination nodes (dt.: Zielknoten) — wie {{ domxref("AudioDestinationNode") }} — haben einen Wert von  0 für diese Eigenschaft.
+
+ +
+
{{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/de/web/api/audiotrack/index.html b/files/de/web/api/audiotrack/index.html new file mode 100644 index 0000000000..3ef55d93ad --- /dev/null +++ b/files/de/web/api/audiotrack/index.html @@ -0,0 +1,86 @@ +--- +title: AudioTrack +slug: Web/API/AudioTrack +translation_of: Web/API/AudioTrack +--- +
{{APIRef("HTML DOM")}}
+ +

Das AudioTrack Interface stellt einen einzelnen Audiotrack aus einem der HTML-Medienelemente {{HTMLElement("audio")}} oder {{HTMLElement("video")}} dar. Die häufigste Verwendung für ein AudioTrack Objekt ist das (De-)Aktivieren seiner Eigenschaft {{domxref("AudioTrack.enabled", "enabled")}} um den Track stummzuschalten.

+ +

Eigenschaften

+ +
+
{{domxref("AudioTrack.enabled", "enabled")}}
+
Ein Boolescher Wert, der kontrolliert ob der Sound für den Audiotrack aktiviert ist. Steht dieser Wert auf  false, ist der Ton stummgeschaltet.
+
{{domxref("AudioTrack.id", "id")}} {{ReadOnlyInline}}
+
Eine {{domxref("DOMString")}}, die den Track eindeutig innerhalb des Mediums identifiziert. Diese ID kann genutzt werden, um einen bestimmten Track auf einer Audio-Track-Liste durch Aufruf von {{domxref("AudioTrackList.getTrackById()")}} zu finden. Die ID kann auch als Fragment der URL genutzt werden, wenn das Medium die Suche per Medienfragment laut Media Fragments URI-Spezifikation unterstützt.
+
{{domxref("AudioTrack.kind", "kind")}} {{ReadOnlyInline}}
+
Ein {{domxref("DOMString")}}, das bestimmt zu welcher Kategorie ein Track gehört. Der Haupt-Audiotrack hätte bspw. als kind die Eigenschaft "main".
+
{{domxref("AudioTrack.label", "label")}} {{ReadOnlyInline}}
+
Ein {{domxref("DOMString")}}, das ein visuelles Label für den Track anzeigt. Z.B. hätte ein Audiokommentar-Track für einen Film als label  "Kommentar mit Regisseur Max Mustermann und den Schauspielern XYZ und ZYX." Dieser String bleibt leer, wenn kein Label angegeben wurde.
+
{{domxref("AudioTrack.language", "language")}} {{ReadOnlyInline}}
+
A {{domxref("DOMString")}} specifying the audio track's primary language, or an empty string if unknown. The language is specified as a BCP 47 ({{RFC(5646)}}) language code, such as "en-US" or "pt-BR".
+
{{domxref("AudioTrack.sourceBuffer", "sourceBuffer")}} {{ReadOnlyInline}}
+
The {{domxref("SourceBuffer")}} that created the track. Returns null if the track was not created by a {{domxref("SourceBuffer")}} or the {{domxref("SourceBuffer")}} has been removed from the {{domxref("MediaSource.sourceBuffers")}} attribute of its parent media source.
+
+ +

Usage notes

+ +

To get an AudioTrack for a given media element, use the element's {{domxref("HTMLMediaElement.audioTracks", "audioTracks")}} property, which returns an {{domxref("AudioTrackList")}} object from which you can get the individual tracks contained in the media:

+ +
var el = document.querySelector("video");
+var tracks = el.audioTracks;
+
+ +

You can then access the media's individual tracks using either array syntax or functions such as {{jsxref("Array.forEach", "forEach()")}}.

+ +

This first example gets the first audio track on the media:

+ +
var firstTrack = tracks[0];
+ +

The next example scans through all of the media's audio tracks, enabling any that are in the user's preferred language (taken from a variable userLanguage) and disabling any others.

+ +
tracks.forEach(function(track) {
+  if (track.language === userLanguage) {
+    track.enabled = true;
+  } else {
+    track.enabled = false;
+  }
+});
+
+ +

The {{domxref("AudioTrack.language", "language")}} is in standard ({{RFC(5646)}}) format. For US English, this would be "en-US", for example.

+ +

Example

+ +

{{page("/en-US/docs/Web/API/AudioTrack/label", "Example")}}

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'media.html#audiotrack', 'AudioTrack')}}{{Spec2('HTML WHATWG')}} 
{{SpecName('HTML5 W3C', 'embedded-content-0.html#audiotrack', 'AudioTrack')}}{{Spec2('HTML5 W3C')}} 
+ +

Browser compatibility

+ + + +

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

diff --git a/files/de/web/api/battery_status_api/index.html b/files/de/web/api/battery_status_api/index.html new file mode 100644 index 0000000000..498c8bb6ae --- /dev/null +++ b/files/de/web/api/battery_status_api/index.html @@ -0,0 +1,92 @@ +--- +title: Battery Status API +slug: Web/API/Battery_Status_API +translation_of: Web/API/Battery_Status_API +--- +

{{DefaultAPISidebar("Battery API")}}{{Obsolete_Header}}

+ +

Die Battery Status API, oder kurz Battery API, stellt Informationen über den Ladezustand der Systembatterie zur Verfügung. Diese Informationen können zur Anpassung der Ressourcennutzung verwendet werden. Wenn nur noch wenig Energie zur Verfügung steht, sollten unnötige Operationen eingestellt werden, damit die Laufzeit erhöht wird. Oder aber der Zustand gespeichert werden, damit ein Datenverlust verhindert werden kann.

+ +

Die Battery Status API erweitert  {{domxref("window.navigator")}} mit einer Methode  {{domxref("navigator.getBattery()")}}, die ein Promise mit einem  {{domxref("BatteryManager")}} Objekt liefert, sowie einigen Nachrichten zum Überwachen des Batteriestatus.

+ +

Beispiel

+ +

In diesem Beispiel wird der Ladezustand (Netz, ladend, etc.) und Änderungen des Batterieniveaus und der Zeit überwacht. Dies erfolgt durch Überwachen der Events:  {{event("chargingchange")}}, {{event("levelchange")}} und {{event("chargingtimechange")}}, {{event("dischargingtimechange")}}.

+ +
navigator.getBattery().then(function(battery) {
+  function updateAllBatteryInfo(){
+    updateChargeInfo();
+    updateLevelInfo();
+    updateChargingInfo();
+    updateDischargingInfo();
+  }
+  updateAllBatteryInfo();
+
+  battery.addEventListener('chargingchange', function(){
+    updateChargeInfo();
+  });
+  function updateChargeInfo(){
+    console.log("Battery charging? "
+                + (battery.charging ? "Yes" : "No"));
+  }
+
+  battery.addEventListener('levelchange', function(){
+    updateLevelInfo();
+  });
+  function updateLevelInfo(){
+    console.log("Battery level: "
+                + battery.level * 100 + "%");
+  }
+
+  battery.addEventListener('chargingtimechange', function(){
+    updateChargingInfo();
+  });
+  function updateChargingInfo(){
+    console.log("Battery charging time: "
+                 + battery.chargingTime + " seconds");
+  }
+
+  battery.addEventListener('dischargingtimechange', function(){
+    updateDischargingInfo();
+  });
+  function updateDischargingInfo(){
+    console.log("Battery discharging time: "
+                 + battery.dischargingTime + " seconds");
+  }
+
+});
+
+ +

Siehe auch die Beispiel in der Spezifikation.

+ +

Spezifikationen

+ + + + + + + + + + + + + + + + +
SpezifikationStatusKommentar
{{SpecName("Battery API")}}{{Spec2("Battery API")}}Initiale Definition.
+ +

Browser Kompatibilität

+ + + +

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

+ +

Siehe auch

+ + diff --git a/files/de/web/api/blob/index.html b/files/de/web/api/blob/index.html new file mode 100644 index 0000000000..352c978ac5 --- /dev/null +++ b/files/de/web/api/blob/index.html @@ -0,0 +1,245 @@ +--- +title: Blob +slug: Web/API/Blob +tags: + - API + - Files + - Reference + - TopicStub + - checkTranslation +translation_of: Web/API/Blob +--- +

{{ APIRef("File API") }}

+ +

Übersicht

+ +

Ein Blob ist eine dateiähnliche Menge unveränderlicher Roh-Daten, die nicht notwendigerweise native JavaScript-Daten enthalten. Das {{ domxref("File") }}-Interface basiert auf Blob und erweitert dessen Funktionen und die Unterstützung von Dateien auf dem System des Nutzers.

+ +

Eine einfache Methode, um einen Blob zu erstellen, ist der Aufruf des {{domxref("Blob.Blob", "Blob()")}}-Konstruktors. Anders ist es auch mit Hilfe eines Aufrufs von slice() möglich, einen Ausschnitt aus einem anderen Blob zu erhalten.

+ +

Die APIs, welche Blob-Objekte akzeptieren, werden ebenfalls in der {{domxref("File")}}-Dokumentation genannt.

+ +
+

Note: The slice() method had initially taken length as the second argument to indicate the number of bytes to copy into the new Blob. If you specified values such that start + lengthexceeded the size of the source Blob, the returned Blob contained data from the start index to the end of the source Blob.

+
+ +
+

Zu beachten: Der slice()-Methode kann in manchen Browsern (und Versionen) ein Vendor-Präfix vorangestellt sein. Firefox 12 und früher: blob.mozSlice(). Safari: blob.webkitSlice(). Eine alte Version von slice() ohne Vendor-Präfix ist überholt. Die Unterstützung von blob.mozSlice() wurde mit Firefox 30 eingestellt.

+
+ +

Konstruktor

+ +
+
{{domxref("Blob.Blob", "Blob()")}}
+
Gibt einen neuen Blob zurück, dessen Inhalt das als Parameter übergebene Array in zusammengesetzter Form ist.
+
+ +

Eigenschaften

+ +
+
{{domxref("Blob.isClosed")}} {{readonlyinline}} {{experimental_inline}}
+
Gibt einen booleschen Wert zurück, der anzeigt, ob die {{domxref("Blob.close()")}}-Methode zu diesem Blob bereits aufgerufen wurde. Geschlossene Blobs können nicht mehr ausgelesen werden.
+
{{domxref("Blob.size")}} {{readonlyinline}}
+
Gibt die Größe des Blob-Inhalts in Bytes zurück.
+
{{domxref("Blob.type")}} {{readonlyinline}}
+
Ein String, der den MIME-Typ enthält. Ist der Typ unbekannt, ist der Rückgabe-String leer.
+
+ +

Methoden

+ +
+
{{domxref("Blob.close()")}} {{experimental_inline}}
+
Schließt das Blob-Objekt und gibt gegebenenfalls reservierte Ressourcen frei.
+
{{domxref("Blob.slice()", "Blob.slice([start[, end[, contentType]]])")}}
+
Gibt ein neues Blob-Objekt zurück, das die spezifierte Menge an Daten enthält.
+
+ +

Beispiele:

+ +

Beispielanwendung des Blob-Konstruktors

+ +

Der {{domxref("Blob.Blob", "Blob() constructor")}} ermöglicht es, Blobs aus Objekten zu erzeugen. Beispielsweise kann man einen Blob von einem String-Objekt erzeugen:

+ +
var debug = {hello: "world"};
+var blob = new Blob([JSON.stringify(debug, null, 2)], {type : 'application/json'});
+
+ +
+

{{ domxref("BlobBuilder") }} bietet noch eine weitere Möglichkeit Blobs zu erstellen, welche mittlerweile allerdings veraltet ist und nicht mehr genutzt werden sollte.

+ +
+
var builder = new BlobBuilder();
+var fileParts = ['<a id="a"><b id="b">hey!</b></a>'];
+builder.append(fileParts[0]);
+var myBlob = builder.getBlob('text/xml');
+
+
+ +

Erstellen einer URL für ein "typed array" durch einen Blob

+ +

Beispiel-Code:

+ +
var typedArray = EinTypedArrayErstellen();
+var blob = new Blob([typedArray], {type: 'application/octet-binary'}); // ein gültiger MIME-Typ
+var url = URL.createObjectURL(blob);
+// Die URL wird etwa so sein: blob:d3958f5c-0777-0845-9dcf-2cb28783acaf
+// Nun kann die URL überall genutzt werden, wo URLs verwendung finden, z.B. in Bildquellen (image.src)
+
+ +

Daten aus einem Blob lesen

+ +

Um Daten aus einem Blob zu lesen, muss ein {{domxref("FileReader")}} genutzt werden. Der folgende Code liest den Inhalt eines Blobs als ein typisiertes Array aus.

+ +
var reader = new FileReader();
+reader.addEventListener("loadend", function() {
+   // reader.result beinhaltet den Inhalt des Blobs
+});
+reader.readAsArrayBuffer(blob);
+ +

Über eine andere Methode von {{domxref("FileReader")}} ist es möglich, den Inhalt eines Blobs als String oder Data-URL zu lesen.

+ +

Spezifikationen

+ + + + + + + + + + + + + + +
SpezifikationStatusHinweis
{{SpecName('File API','#blob','Blob')}}{{Spec2('File API')}}Grundlegende Definition
+ +

Browser-Kompatibilität

+ +

{{CompatibilityTable}}

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support5[1]4[2]1011.10[1]5.1[1]
slice()10 {{property_prefix("webkit")}}
+ 21
5 {{property_prefix("moz")}}[3]
+ 13
10125.1 {{property_prefix("webkit")}}
Blob()constructor20{{CompatGeckoDesktop("13.0")}}1012.106
close()and isClosed{{CompatUnknown}}{{CompatNo}}[4]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatGeckoMobile("13.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
slice(){{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Blob()constructor{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
close()and isClosed{{CompatUnknown}}{{CompatNo}}[4]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+  
+ +

Anmerkung zur slice()-Implementierung

+ +

[1] Eine Version von slice(), die als zweites Argument die gewünschte Größe enthält, war in WebKit und Opera 11.10 implementiert. Da sich jedoch diese Syntax von {{jsxref("Array/slice", "Array.slice()")}} und {{jsxref("String/slice", "String.slice()")}} unterschied, wurde die Unterstützung in WebKit fallen gelassen zu Gunsten der neuen Syntax von Blob.webkitSlice().

+ +

[2] Eine Variante von slice(), die als zweites Argument die gewünschte Größe enthält, war in Firefox 4 verfügbar. Da sich jedoch diese Syntax von {{jsxref("Array/slice", "Array.slice()")}} und {{jsxref("String/slice", "String.slice()")}} unterschied, wurde diese Unterstützung in Gecko fallen gelassen zu Gunsten der neuen Syntax von mozSlice().

+ +

[3] Vor Gecko 12.0 {{ geckoRelease("12.0") }} trat ein Fehler im Verhalten von slice() auf; die erste und letzte Position außerhalb des Bereichs von 64-Bit-Werten wurden fehlerhaft verarbeitet, was nun für vorzeichenlose 64-Bit-Werte behoben wurde.

+ +

[4] Siehe {{bug("1048325")}}

+ +

Anmerkungen zu Gecko

+ +

Vor Gecko 12.0 {{ geckoRelease("12.0") }} gab es einen Bug, der das Verhalten von {{ manch("slice") }} beinflusste. Bei Start- und Endpositionen außerhalb von vorzeichenbehafteten 64-Bit-Werten funktionierte die Methode nicht. Dieser Bug wurde mittlerweile behoben und vorzeichenlose 64-Bit-Werte sind nun möglich.

+ +

Chrome Code - Scope

+ +

Um Blobs im Chrome Code, JSM und Bootstrap Scope zu verwenden, müssen sie folgendermaßen importiert werden:

+ +
Cu.importGlobalProperties(['Blob']);
+
+ +

Blobs sind auch in Worker-Scopes verfügbar.

+ +

Siehe auch

+ + diff --git a/files/de/web/api/body/arraybuffer/index.html b/files/de/web/api/body/arraybuffer/index.html new file mode 100644 index 0000000000..7550dfadc8 --- /dev/null +++ b/files/de/web/api/body/arraybuffer/index.html @@ -0,0 +1,87 @@ +--- +title: Body.arrayBuffer() +slug: Web/API/Body/arrayBuffer +translation_of: Web/API/Body/arrayBuffer +--- +
{{APIRef("Fetch")}}
+ +

Die Methode arrayBuffer() des {{domxref("Body")}} Mixin nimmt einen {{domxref("Response")}} Stream und liest ihn bis zum Ende. Sie gibt ein Promise zurück, welches in einen {{domxref("ArrayBuffer")}} aufgelöst wird.

+ +

Syntax

+ +
response.arrayBuffer().then(function(buffer) {
+  // mach etwas mit dem Buffer
+});
+ +

Parameter

+ +

Keine.

+ +

Rückgabewert

+ +

Ein Promise, welches in einen {{domxref("ArrayBuffer")}} aufgelöst wird.

+ +

Beispiel

+ +

In unserem Live-Beispiel zum Abruf eines Array Buffers haben wir einen Wiedergabe-Knopf. Bei einem Klick darauf wird die Funktion getData() ausgeführt. Beachten Sie, dass vor der Wiedergabe die ganze Audio-Datei heruntergeladen wird. Benötigen Sie eine Wiedergabe noch während des Downloads (Streaming) ziehen Sie {{domxref("HTMLAudioElement")}} in Betracht:

+ +
new Audio(music.ogg).play()
+
+ +

In getData() erstellen wir eine neue Anfrage mit dem {{domxref("Request.Request")}} Konstruktor, um dann einen OGG Musik-Track abzurufen. Wir benutzen ebenfalls {{domxref("AudioContext.createBufferSource")}} um eine Audio-Puffer-Quelle zu erstellen. Ist der Abruf erfolgreich, lesen wir mit arrayBuffer() einen {{domxref("ArrayBuffer")}} aus der Antwort, dekodieren die Audiodaten mit {{domxref("AudioContext.decodeAudioData")}}, setzen die dekodierten Daten als Quelle für den Audio-Puffer fest und verbinden die Quelle mit {{domxref("AudioContext.destination")}}.

+ +

Wenn getData() durchgelaufen ist, starten wir die Wiedergabe mit start(0) und deaktivieren den Wiedergabe-Knopf, damit er nicht erneut geklickt werden kann, während die Wiedergabe läuft (was zu einem Fehler führen würde).

+ +
function getData() {
+  source = audioCtx.createBufferSource();
+
+  var myRequest = new Request('viper.ogg');
+
+  fetch(myRequest).then(function(response) {
+    return response.arrayBuffer();
+  }).then(function(buffer) {
+    audioCtx.decodeAudioData(buffer, function(decodedData) {
+      source.buffer = decodedData;
+      source.connect(audioCtx.destination);
+    });
+  });
+};
+
+// Knöpfe zum Abspielen und Anhalten verknüpfen
+
+play.onclick = function() {
+  getData();
+  source.start(0);
+  play.setAttribute('disabled', 'disabled');
+}
+ +

Spezifikationen

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Fetch','#dom-body-arraybuffer','arrayBuffer()')}}{{Spec2('Fetch')}} 
+ +

Browserkompatibilität

+ + + +

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

+ +

Siehe auch

+ + diff --git a/files/de/web/api/body/blob/index.html b/files/de/web/api/body/blob/index.html new file mode 100644 index 0000000000..53595fdbda --- /dev/null +++ b/files/de/web/api/body/blob/index.html @@ -0,0 +1,73 @@ +--- +title: Body.blob() +slug: Web/API/Body/blob +translation_of: Web/API/Body/blob +--- +
{{APIRef("Fetch")}}
+ +

Die Methode blob() des {{domxref("Body")}} Mixin nimmt einen {{domxref("Response")}} Stream und liest ihn bis zum Ende. Sie gibt ein Promise zurück, welches in einen {{domxref("Blob")}} aufgelöst wird.

+ +

Syntax

+ +
response.blob().then(function(myBlob) {
+  // mach etwas mit myBlob
+});
+ +

Parameter

+ +

Keine.

+ +
Hinweis: Wenn die {{domxref("Response")}} vom {{domxref("Response.type")}} her "opaque" ist, hat der resultierende {{domxref("Blob")}} eine {{domxref("Blob.size")}} von 0 und einen {{domxref("Blob.type")}} eines leeren Strings "", wodurch er für Methoden wie {{domxref("URL.createObjectURL")}} unbrauchbar wird.
+ +

Rückgabewert

+ +

Ein Promise, welches in einen {{domxref("Blob")}} aufgelöst wird.

+ +

Beispiel

+ +

In unserem Beispiel für eine Fetch Anfrage (live ausführen) erstellen wir eine neue Anfrage mit dem {{domxref("Request.Request")}} Konstruktor und rufen dann ein JPG ab. Wenn der Abruf erfolgreich ist, lesen wir mit blob() einen {{domxref("Blob")}} aus der Antwort, fügen ihn mit {{domxref("URL.createObjectURL")}} in eine Objekt-URL ein und legen diese URL als Quelle für das {{htmlelement("img")}} Element zum Anzeigen des Bildes fest.

+ +
var myImage = document.querySelector('img');
+
+var myRequest = new Request('flowers.jpg');
+
+fetch(myRequest)
+.then(function(response) {
+  return response.blob();
+})
+.then(function(myBlob) {
+  var objectURL = URL.createObjectURL(myBlob);
+  myImage.src = objectURL;
+});
+
+ +

Spezifikationen

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Fetch','#dom-body-blob','blob()')}}{{Spec2('Fetch')}} 
+ +

Browserkompatibilität

+ + + +

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

+ +

Siehe auch

+ + diff --git a/files/de/web/api/body/body/index.html b/files/de/web/api/body/body/index.html new file mode 100644 index 0000000000..cbe7484d91 --- /dev/null +++ b/files/de/web/api/body/body/index.html @@ -0,0 +1,86 @@ +--- +title: Body.body +slug: Web/API/Body/body +translation_of: Web/API/Body/body +--- +
{{APIRef("Fetch")}}{{seecompattable}}
+ +

Die schreibgeschützte body Eigenschaft des {{domxref("Body")}} Mixin ist ein einfacher Getter, der dazu benutzt wird den Inhalt des Body als {{domxref("ReadableStream")}} bereitzustellen.

+ +

Syntax

+ +
var stream = responseInstance.body;
+ +

Wert

+ +

Ein {{domxref("ReadableStream")}}.

+ +

Beispiel

+ +

In unserem einfachen Stream-Pump-Beispiel rufen wir ein Bild ab, machen den Antwort-Stream mit response.body sichtbar, erstellen einen Reader mit {{domxref("ReadableStream.getReader()")}} und reihen die Teile des Streams in einen zweiten, benutzerdefinierten, lesbaren Stream — wodurch wie eine exakte Kopie des Bilds erhalten.

+ +
const image = document.getElementById('target');
+
+// Bild holen
+fetch('./tortoise.png')
+// Body als ReadableStream abrufen
+.then(response => response.body)
+.then(body => {
+  const reader = body.getReader();
+
+  return new ReadableStream({
+    start(controller) {
+      return pump();
+
+      function pump() {
+        return reader.read().then(({ done, value }) => {
+          // Stream schließen, wenn keine weiteren Daten verarbeitet werden müssen
+          if (done) {
+            controller.close();
+            return;
+          }
+
+          // Das nächste Datenstück in unseren Ziel-Stream einreihen
+          controller.enqueue(value);
+          return pump();
+        });
+      }
+    }
+  })
+})
+.then(stream => new Response(stream))
+.then(response => response.blob())
+.then(blob => URL.createObjectURL(blob))
+.then(url => console.log(image.src = url))
+.catch(err => console.error(err));
+ +

Spezifikationen

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

Browserkompatibilität

+ + + +

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

+ +

Siehe auch

+ + diff --git a/files/de/web/api/body/bodyused/index.html b/files/de/web/api/body/bodyused/index.html new file mode 100644 index 0000000000..052e8fcc7c --- /dev/null +++ b/files/de/web/api/body/bodyused/index.html @@ -0,0 +1,73 @@ +--- +title: Body.bodyUsed +slug: Web/API/Body/bodyUsed +translation_of: Web/API/Body/bodyUsed +--- +
{{APIRef("Fetch")}}
+ +

Die schreibgeschützte bodyUsed Eigenschaft des {{domxref("Body")}} Mixin enthält einen {{domxref("Boolean")}} der angibt, ob der Body schon eingelesen wurde.

+ +

Syntax

+ +
var myBodyUsed = response.bodyUsed;
+ +

Wert

+ +

Ein {{domxref("Boolean")}}.

+ +

Beispiel

+ +

In unserem Beispiel für eine Fetch Anfrage (live ausführen) erstellen wir eine neue Anforderung mit dem {{domxref("Request.Request")}} Konstruktor und rufen dann ein JPG ab. Wenn der Abruf erfolgreich ist, lesen wir mit blob() einen {{domxref("Blob")}} aus der Antwort, fügen ihn mit {{domxref("URL.createObjectURL")}} in eine Objekt-URL ein und legen diese URL als Quelle für das {{htmlelement("img")}} Element zum Anzeigen des Bildes fest.

+ +

Beachten Sie, dass wir response.bodyUsed vor dem Aufruf von response.blob () und einmal danach in der Konsole protokollieren. Dies gibt vorher false zurück und anschließend true, da der Body ab diesem Punkt gelesen wurde.

+ +

HTML Inhalt

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

JavaScript Inhalt

+ +
var myImage = document.querySelector('.my-image');
+fetch('https://upload.wikimedia.org/wikipedia/commons/7/77/Delete_key1.jpg').then(function(response) {
+    console.log(response.bodyUsed);
+    var res = response.blob();
+    console.log(response.bodyUsed);
+    return res;
+}).then(function(response) {
+    var objectURL = URL.createObjectURL(response);
+    myImage.src = objectURL;
+});
+ +

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

+ +

Spezifikationen

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Fetch','#dom-body-bodyused','bodyUsed')}}{{Spec2('Fetch')}} 
+ +

Browserkompatibilität

+ + + +

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

+ +

Siehe auch

+ + diff --git a/files/de/web/api/body/formdata/index.html b/files/de/web/api/body/formdata/index.html new file mode 100644 index 0000000000..4ceb02aeb4 --- /dev/null +++ b/files/de/web/api/body/formdata/index.html @@ -0,0 +1,62 @@ +--- +title: Body.formData() +slug: Web/API/Body/formData +translation_of: Web/API/Body/formData +--- +
{{APIRef("Fetch")}}
+ +

Die Methode formData() des {{domxref("Body")}} Mixin nimmt einen {{domxref("Response")}} Stream und liest ihn bis zum Ende. Sie gibt ein Promise zurück, welches in ein {{domxref("FormData")}} Objekt aufgelöst wird.

+ +
+

Hinweis: Dies ist hauptsächlich für Service Worker relevant. Wenn ein Benutzer ein Formular absendet und ein Service Worker die Anfrage abfängt, könnten Sie bspw. formData() aufrufen, um eine Key-Value-Abbildung zu erhalten, einige Felder zu modifizieren und das Formular dann an den Server weiterzuschicken (oder lokal zu benutzen).

+
+ +

Syntax

+ +
response.formData()
+.then(function(formdata) {
+  // machen Sie etwas mit Ihren Formulardaten
+});
+ +

Parameter

+ +

Keine.

+ +

Rückgabewert

+ +

Ein Promise, welches in ein {{domxref("FormData")}} Objekt aufgelöst wird.

+ +

Beispiel

+ +

Wird nachgereicht.

+ +

Spezifikationen

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Fetch','#dom-body-formdata','formData()')}}{{Spec2('Fetch')}} 
+ +

Browserkompatibilität

+ + + +

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

+ +

Siehe auch

+ + diff --git a/files/de/web/api/body/index.html b/files/de/web/api/body/index.html new file mode 100644 index 0000000000..3693a73653 --- /dev/null +++ b/files/de/web/api/body/index.html @@ -0,0 +1,99 @@ +--- +title: Body +slug: Web/API/Body +tags: + - API + - BODY + - Experimental + - Fetch + - Fetch API + - Interface + - NeedsTranslation + - Reference + - TopicStub + - request +translation_of: Web/API/Body +--- +
{{ 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 {{domxref("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 {{domxref("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/de/web/api/body/json/index.html b/files/de/web/api/body/json/index.html new file mode 100644 index 0000000000..76271e680d --- /dev/null +++ b/files/de/web/api/body/json/index.html @@ -0,0 +1,73 @@ +--- +title: Body.json() +slug: Web/API/Body/json +translation_of: Web/API/Body/json +--- +
{{APIRef("Fetch")}}
+ +

Die Methode json() des {{domxref("Body")}} Mixin nimmt einen {{domxref("Response")}} Stream und liest ihn bis zum Ende. Sie gibt ein Promise zurück, welches den Inhalt des Body als {{jsxref("JSON")}} einliest.

+ +

Syntax

+ +
response.json().then(function(data) {
+  // mach etwas mit data
+});
+ +

Parameter

+ +

Keine.

+ +

Rückgabewert

+ +

Ein Promise, welches den Inhalt des Body als {{jsxref("JSON")}} einliest. Dies kann alles sein, was als JSON abgebildet werden kann — ein Objekt, ein Array, ein String, eine Zahl...

+ +

Beispiel

+ +

In unserem Beispiel für den Abruf eines json (live ausführen) erstellen wir eine neue Anfrage mit dem {{domxref("Request.Request")}} Konstruktor und rufen dann eine .json Datei ab. Wenn der Abruf erfolgreich ist lesen wir die Daten ein und parsen sie mit json(), lesen die Werte erwartungsgemäß aus und fügen sie in eine Liste ein um unsere Produktdaten anzuzeigen.

+ +
var myList = document.querySelector('ul');
+
+var myRequest = new Request('products.json');
+
+fetch(myRequest)
+  .then(function(response) { return response.json(); })
+  .then(function(data) {
+    for (var i = 0; i < data.products.length; i++) {
+      var listItem = document.createElement('li');
+      listItem.innerHTML = '<strong>' + data.products[i].Name + '</strong> befindet sich in ' +
+                           data.products[i].Location +
+                           '. Preis: <strong>' + data.products[i].Price + '€</strong>';
+      myList.appendChild(listItem);
+    }
+  });
+ +

Spezifikationen

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Fetch','#dom-body-json','json()')}}{{Spec2('Fetch')}} 
+ +

Browserkompatibilität

+ + + +

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

+ +

Siehe auch

+ + diff --git a/files/de/web/api/body/text/index.html b/files/de/web/api/body/text/index.html new file mode 100644 index 0000000000..8ccc5fb358 --- /dev/null +++ b/files/de/web/api/body/text/index.html @@ -0,0 +1,80 @@ +--- +title: Body.text() +slug: Web/API/Body/text +translation_of: Web/API/Body/text +--- +
{{APIRef("Fetch")}}
+ +

Die Methode text() des {{domxref("Body")}} Mixin nimmt einen {{domxref("Response")}} Stream und liest ihn bis zum Ende. Sie gibt ein Promise zurück, welches in ein {{domxref("USVString")}} Objekt (Text) aufgelöst wird. Die Antwort wird immer mit UTF-8 dekodiert.

+ +

Syntax

+ +
response.text().then(function (text) {
+  // do something with the text response
+});
+ +

Parameter

+ +

Keine.

+ +

Rückgabewert

+ +

Ein Promise, welches in einen {{domxref("USVString")}} aufgelöst wird.

+ +

Beispiel

+ +

In unserem Beispiel für den Abruf von Text (live ausführen) haben wir ein {{htmlelement("article")}} Element und drei Links (im Array myLinks gespeichert). Zuerst durchlaufen wir all diese, damit alle einen onclick Event Handler bekommen, der die Funktion getData() ausführt — der Bezeichner data-page des Links wird dabei als Argument übergeben — wenn einer der Links geklickt wird.

+ +

Wenn getData() ausgeführt wird erstellen wie eine Anfrage mit dem {{domxref("Request.Request")}} Konstruktor und rufen dann eine .txt Datei ab. Wenn der Abruf erfolgreich ist lesen wir das {{jsxref("USVString")}} (Text) Objekt aus der Antwort mit text() und setzen dann {{domxref("Element.innerHTML","innerHTML")}} des {{htmlelement("article")}} Elements auf den Wert des Text-Objekts.

+ +
var myArticle = document.querySelector('article');
+var myLinks = document.querySelectorAll('ul a');
+
+for(i = 0; i <= myLinks.length-1; i++) {
+  myLinks[i].onclick = function(e) {
+    e.preventDefault();
+    var linkData = e.target.getAttribute('data-page');
+    getData(linkData);
+  }
+};
+
+function getData(pageId) {
+  console.log(pageId);
+  var myRequest = new Request(pageId + '.txt');
+  fetch(myRequest).then(function(response) {
+    return response.text().then(function(text) {
+      myArticle.innerHTML = text;
+    });
+  });
+}
+ +

Spezifikationen

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Fetch','#dom-body-text','text()')}}{{Spec2('Fetch')}} 
+ +

Browserkompatibilität

+ + + +

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

+ +

Siehe auch

+ + diff --git a/files/de/web/api/cache/add/index.html b/files/de/web/api/cache/add/index.html new file mode 100644 index 0000000000..778820ca66 --- /dev/null +++ b/files/de/web/api/cache/add/index.html @@ -0,0 +1,106 @@ +--- +title: Cache.add() +slug: Web/API/Cache/add +translation_of: Web/API/Cache/add +--- +

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

+ +

Die add() Methode des {{domxref("Cache")}} Interface nimmt eine URL, ruft sie ab und fügt das resultierende Objekt zum gegebenen Cache. Die add() Methode gleicht funktional dem folgenden:

+ +
fetch(url).then(function(response) {
+  if (!response.ok) {
+    throw new TypeError('bad response status');
+  }
+  return cache.put(url, response);
+})
+ +

Für komplexere Operationen müssen Sie {{domxref("Cache.put","Cache.put()")}} direkt verwenden.

+ +
+

Hinweis: add() wird alle zuvor im Cache gespeicherten Schlüssel-Wert-Paare die der Request gleichen überschreiben.

+
+ +

Syntax

+ +
cache.add(request).then(function() {
+  // request wurde dem Cache hinzugefügt
+});
+
+ +

Parameter

+ +
+
request
+
Die Request, die dem Cache hinzugefügt werden soll. Dies kann ein {{domxref("Request")}} Objekt oder eine URL sein.
+
+ +

Rückgabewert

+ +

Eine {{jsxref("Promise")}}, die auf void auflöst.

+ +

Exceptions

+ + + + + + + + + + + + + + +
ExceptionTritt auf wenn
TypeError +

Das URL-Schema nicht http oder https ist.

+ +

Der Antwortstatus ist nicht im 200 Bereich (d.h. keine erfolgreiche Antwort) Dies tritt auf, wenn die Request nicht erfolgreich zurückgegeben wird aber auch wenn die Request eine cross-origin no-cors Request ist (In diesem Fall ist der Status immer 0.)

+
+ +

Beispiele

+ +

Dieser Codeblock wartet darauf, dass ein {{domxref("InstallEvent")}} ausgelöst wird, ruft dann {{domxref("ExtendableEvent.waitUntil","waitUntil()")}} auf, um den Installationsprozess der Applikation einzuleiten. Dies beinhaltet den Aufruf von {{domxref("CacheStorage.open")}} um einen neuen Cache zu erstellen, um dann mittels {{domxref("Cache.add")}} etwas zu diesem hinzuzufügen.

+ +
this.addEventListener('install', function(event) {
+  event.waitUntil(
+    caches.open('v1').then(function(cache) {
+      return cache.add('/sw-test/index.html');
+    })
+  );
+});
+
+ +

Spezifikationen

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Service Workers', '#dom-cache-add', 'Cache: add')}}{{Spec2('Service Workers')}}Erstdefinition.
+ +

Browserkompatibilität

+ +
+ + +

{{Compat("api.Cache.add")}}

+
+ +

Weiterlesen

+ + diff --git a/files/de/web/api/cache/addall/index.html b/files/de/web/api/cache/addall/index.html new file mode 100644 index 0000000000..78467ff40f --- /dev/null +++ b/files/de/web/api/cache/addall/index.html @@ -0,0 +1,212 @@ +--- +title: Cache.addAll() +slug: Web/API/Cache/addAll +tags: + - Cache + - Experimentell + - Methoden + - Referenz + - Service Worker +translation_of: Web/API/Cache/addAll +--- +

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

+ +

Zusammenfassung

+ +

Die addAll() Methode der {{domxref("Cache")}} Schnittstelle nimmt ein Array von URLS,  ruft diese ab und fügt die daraus resultierenden Antwortobjekte zum jeweiligen Cache hinzu. Die Antwortobjekte, welche während des Abrufens erzeugt werden, werden zu Schlüsselwerten für die gespeicherten Antwortoperationen. 

+ +
+

HinweisaddAll() überschreibt jegliche Schlüsselwertpaare im Cache, die der Anfrage entsprechen wird aber scheitern, wenn eine resultierende put() Operation einen früheren Cache-Eintrag, der durch die gleiche addAll() Methode erzeugt wurde, überschreiben würde.

+
+ +
+

Hinweis: Ursprüngliche Cache Implementationen (sowohl in Blink als auch in Gecko) lösen {{domxref("Cache.add")}}, {{domxref("Cache.addAll")}}, und {{domxref("Cache.put")}}  Promises auf, wenn die jeweilige Antwort vollständig in den Speicher geschrieben wurde. Neuere Spezifikationsversionen haben aktualisierte Informationen, welche aussagen, dass der Browser den Promise bereits auflösen kann, wenn der Eintrag in die Datenbank erfolgt, auch wenn die Antwort  zu diesem Zeitpunkt noch nicht vollständig geschrieben wurde (sprich der Datenstrom in den Speicher ist noch nicht beendet).

+
+ +
+

Hinweis:  Zum Stand von Chrome 46 wird die Cache API nur Anfragen von sicheren Quellen speichern, also solche die via HTTPS angeboten werden.

+
+ +

Syntax

+ +
cache.addAll(requests[]).then(function() {
+  //Anfragen wurden zum Cache hinzugefügt
+});
+
+ +

Argumente

+ +
+
requests
+
Ein Array von {{domxref("Request")}} Objekten, die Sie zum Cache hinzufügen möchten.
+
+ +

Rückgabewert

+ +

Ein {{jsxref("Promise")}} der mit void auflöst.

+ +

Ausnahmen

+ + + + + + + + + + + + + + +
AusnahmePassiert bei
TypeError +

Das URL Schama ist nicht http oder https.

+ +

Der Antwortstatus ist nicht im 200er Bereich ( nicht erfolgreiche Antwort ). Dies entsteht, wenn die Anfrage nicht erfolreich zurückgibt, aber auch, wenn die Anfrage eine cross-origin no-cors Anfrage ist (in diesem Fall wird immer 0 als Berichtsstatus gegeben).

+
+ +

Beispiele

+ +

Dieser Programmblock wartet auf ein abgesetztes {{domxref("InstallEvent")}} , woraufhin ein {{domxref("ExtendableEvent.waitUntil","waitUntil")}} läuft, das den Installationsprozess für die Applikation handhabt. Das beinhaltet das Aufrufen von {{domxref("CacheStorage.open")}} um einen neuen Cache zu erstellen. Anschließend wird addAll() benutzt um diesem eine Reihe von Ressourcen (in diesem Fall html, css und Bild-Ressourcen) hinzuzufügen.

+ +
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'
+      ]);
+    })
+  );
+});
+
+ +

Spezifikationen

+ + + + + + + + + + + + + + +
SpezifikationStatusKommentar
{{SpecName('Service Workers', '#cache', 'Cache')}}{{Spec2('Service Workers')}}Erste Definition.
+ +

Browserunterstützung

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(46.0)}}{{CompatVersionUnknown}}[1]{{CompatNo}}24{{CompatNo}}
Require HTTPS{{CompatChrome(46.0)}}{{CompatVersionUnknown}}[1]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
TypeError if request is not successful{{CompatVersionUnknown}}{{CompatGeckoDesktop(47.0)}}[1]{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatNo}}{{CompatUnknown}}{{CompatNo}}{{CompatChrome(46.0)}}
Require HTTPS{{CompatNo}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatChrome(46.0)}}
TypeError if request is not successful{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

[1] Service workers (und Push) wurden in Firefox 45 Extended Support Release (ESR.) abgeschaltet.

+ +

Siehe auch

+ + diff --git a/files/de/web/api/cache/index.html b/files/de/web/api/cache/index.html new file mode 100644 index 0000000000..3043baa825 --- /dev/null +++ b/files/de/web/api/cache/index.html @@ -0,0 +1,288 @@ +--- +title: Cache +slug: Web/API/Cache +tags: + - API + - Cache + - Draft + - Experimental + - Interface + - NeedsTranslation + - Offline + - Reference + - Service Workers + - Storage + - TopicStub +translation_of: Web/API/Cache +--- +

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

+ +

The Cache interface provides a storage mechanism for Request / Response object pairs that are cached, for example as part of the {{domxref("ServiceWorker")}} life cycle. Note that the Cache interface is exposed to windowed scopes as well as workers. You don't have to use it in conjunction with service workers, even though it is defined in the service worker spec.

+ +

An origin can have multiple, named Cache objects. You are responsible for implementing how your script (e.g. in a {{domxref("ServiceWorker")}})  handles Cache updates. Items in a Cache do not get updated unless explicitly requested; they don’t expire unless deleted. Use {{domxref("CacheStorage.open", "CacheStorage.open(cacheName)")}} to open a specific named Cache object and then call any of the Cache methods to maintain the Cache.

+ +

You are also responsible for periodically purging cache entries. Each browser has a hard limit on the amount of cache storage that a given origin 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. Make sure to version caches by name and use the caches only from the version of the script that they can safely operate on. See Deleting old caches for more information.

+ +
+

Note: {{domxref("Cache.put")}}, {{domxref("Cache.add")}}, and {{domxref("Cache.addAll")}} only allow GET requests to be stored in the cache.

+
+ +
+

Note: Initial Cache implementations (in both Blink and Gecko) resolve {{domxref("Cache.add")}}, {{domxref("Cache.addAll")}}, and {{domxref("Cache.put")}} promises when the response body is fully written to storage.  More recent spec versions have newer language stating that the browser can resolve the promise as soon as the entry is recorded in the database even if the response body is still streaming in.

+
+ +
+

Note: As of Chrome 46, the Cache API will only store requests from secure origins, meaning those served over HTTPS.

+
+ +
+

Note: The key matching algorithm depends on the VARY header in the value. So matching a new key requires looking at both key and value for entries in the Cache.

+
+ +
+

Note: The caching API doesn't honor HTTP caching headers.

+
+ +

Methods

+ +
+
{{domxref("Cache.match", "Cache.match(request, options)")}}
+
Returns a {{jsxref("Promise")}} that resolves to the response associated with the first matching request in the {{domxref("Cache")}} object.
+
{{domxref("Cache.matchAll", "Cache.matchAll(request, options)")}}
+
Returns a {{jsxref("Promise")}} that resolves to an array of all matching requests in the {{domxref("Cache")}} object.
+
{{domxref("Cache.add", "Cache.add(request)")}}
+
Takes a URL, retrieves it and adds the resulting response object to the given cache. This is fuctionally equivalent to calling fetch(), then using Cache.put() to add the results to the cache.
+
{{domxref("Cache.addAll", "Cache.addAll(requests)")}}
+
Takes an array of URLs, retrieves them, and adds the resulting response objects to the given cache.
+
{{domxref("Cache.put", "Cache.put(request, response)")}}
+
Takes both a request and its response and adds it to the given cache.
+
{{domxref("Cache.delete", "Cache.delete(request, options)")}}
+
Finds the {{domxref("Cache")}} entry whose key is the request, and if found, deletes the {{domxref("Cache")}} entry and returns a {{jsxref("Promise")}} that resolves to true. If no {{domxref("Cache")}} entry is found, it returns false.
+
{{domxref("Cache.keys", "Cache.keys(request, options)")}}
+
Returns a {{jsxref("Promise")}} that resolves to an array of {{domxref("Cache")}} keys.
+
+ +

Examples

+ +

This code snippet is from the service worker selective caching sample. (see selective caching live) The code uses {{domxref("CacheStorage.open", "CacheStorage.open(cacheName)")}} to open any {{domxref("Cache")}} objects with a Content-Type header that starts with font/.

+ +

The code then uses {{domxref("Cache.match", "Cache.match(request, options)")}} to see if there's already a matching font in the cache, and if so, returns it. If there isn't a matching font, the code fetches the font from the network and uses {{domxref("Cache.put","Cache.put(request, response)")}} to cache the fetched resource.

+ +

The code handles exceptions thrown from the {{domxref("Globalfetch.fetch","fetch()")}} operation. Note that a 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.

+ +

The code snippet also shows a best practice for versioning caches used by the service worker. Though there's only one cache in this example, the same approach can be used for multiple caches. It maps a shorthand identifier for a cache to a specific, versioned cache name. The code also deletes all caches that aren't named in CURRENT_CACHES.

+ +
Note: In Chrome, visit chrome://inspect/#service-workers and click on the "inspect" link below the registered service worker to view logging statements for the various actions the service-worker.js script is performing.
+ +
var CACHE_VERSION = 1;
+
+// Shorthand identifier mapped to specific versioned 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];
+  });
+
+  // Active worker won't be treated as activated until promise resolves successfully.
+  event.waitUntil(
+    caches.keys().then(function(cacheNames) {
+      return Promise.all(
+        cacheNames.map(function(cacheName) {
+          if (expectedCacheNames.indexOf(cacheName) == -1) {
+            console.log('Deleting out of date cache:', cacheName);
+
+            return caches.delete(cacheName);
+          }
+        })
+      );
+    })
+  );
+});
+
+self.addEventListener('fetch', function(event) {
+  console.log('Handling fetch event for', event.request.url);
+
+  event.respondWith(
+
+    // Opens Cache objects that start with 'font'.
+    caches.open(CURRENT_CACHES['font']).then(function(cache) {
+      return cache.match(event.request).then(function(response) {
+        if (response) {
+          console.log(' Found response in cache:', response);
+
+          return response;
+        }
+      }).catch(function(error) {
+
+        // Handles exceptions that arise from match() or fetch().
+        console.error('  Error in fetch handler:', error);
+
+        throw error;
+      });
+    })
+  );
+});
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Service Workers', '#cache', 'Cache')}}{{Spec2('Service Workers')}}Initial definition.
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{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}}
Require HTTPS for add(), addAll(), and put(){{CompatChrome(46.0)}}{{CompatVersionUnknown}}[1]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{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)}}
Require HTTPS for add(), addAll(), and put(){{CompatNo}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatChrome(46.0)}}
+
+ +

[1] Service workers (and Push) have been disabled in the Firefox 45 Extended Support Release (ESR.)

+ +

See also

+ + diff --git a/files/de/web/api/canvasrenderingcontext2d/canvas/index.html b/files/de/web/api/canvasrenderingcontext2d/canvas/index.html new file mode 100644 index 0000000000..47b01c8f72 --- /dev/null +++ b/files/de/web/api/canvasrenderingcontext2d/canvas/index.html @@ -0,0 +1,56 @@ +--- +title: CanvasRenderingContext2D.canvas +slug: Web/API/CanvasRenderingContext2D/canvas +translation_of: Web/API/CanvasRenderingContext2D/canvas +--- +
{{APIRef}}
+ +

Die CanvasRenderingContext2D.canvas Eigenschaft, Teil der Canvas API, ist eine Nurlese-Referenz auf das {{domxref("HTMLCanvasElement")}} Objekt, das mit einem gegebenen Kontext assoziiert ist. Sie kann {{jsxref("null")}} sein, wenn kein assoziiertes {{HTMLElement("canvas")}} Element existiert.

+ +

Syntax

+ +
ctx.canvas;
+ +

Beispiele

+ +

Wenn dieses {{HTMLElement("canvas")}} Element gegeben ist:

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

... kannst du eine Referenz auf das Canvas-Element innerhalb von CanvasRenderingContext2D herstellen, indem du die canvas Eigenschaft verwendest.

+ +
var canvas = document.getElementById('canvas');
+var ctx = canvas.getContext('2d');
+ctx.canvas // HTMLCanvasElement
+
+ +

Spezifikationen

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

Browser-Kompatibilität

+ + + +

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

+ +

Siehe auch

+ + diff --git a/files/de/web/api/canvasrenderingcontext2d/fillrect/index.html b/files/de/web/api/canvasrenderingcontext2d/fillrect/index.html new file mode 100644 index 0000000000..178a861f4e --- /dev/null +++ b/files/de/web/api/canvasrenderingcontext2d/fillrect/index.html @@ -0,0 +1,177 @@ +--- +title: CanvasRenderingContext2D.fillRect() +slug: Web/API/CanvasRenderingContext2D/fillRect +tags: + - API + - Canvas + - CanvasRenderingContext2D + - Method + - Methode(2) + - Reference + - Referenz +translation_of: Web/API/CanvasRenderingContext2D/fillRect +--- +
{{APIRef}}
+ +

Die Methode CanvasRenderingContext2D.fillRect() der Canvas 2D API zeichnet ein ausgefülltes Rechteck an der Position (x, y). Die Größe wird über die Parameter width und height bestimmt. Die Füllfarbe wird über das Attribut fillStyle des Context-Objekts festgelegt.

+ +

Syntax

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

Parameter

+ +
+
x
+
Die Koordinate auf der x-Achse als horizontaler Startpunkt des Rechtecks.
+
y
+
Die Koordinate auf der y-Achse als vertikaler Startpunkt des Rechtecks.
+
width
+
Die Breite des Rechtecks.
+
height
+
Die Höhe des Rechtecks.
+
+ +

Beispiele

+ +

Benutzung der Methode fillRect

+ +

Dies ist ein einfaches Code-Beispiel, welches die fillRect Methode nutzt.

+ +

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);
+
+// fill the whole canvas
+// ctx.fillRect(0, 0, canvas.width, canvas.height);
+
+ +

Ändern Sie den unten gezeigten Code und sehen Sie Ihre Änderungen live im Canvas-Element:

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

+ +

Spezifikationen

+ + + + + + + + + + + + + + +
SpezifikationStatusKommentar
{{SpecName('HTML WHATWG', "scripting.html#dom-context-2d-fillrect", "CanvasRenderingContext2D.fillRect")}}{{Spec2('HTML WHATWG')}} 
+ +

Browserkompatibilität

+ +

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

Siehe auch

+ + diff --git a/files/de/web/api/canvasrenderingcontext2d/getimagedata/index.html b/files/de/web/api/canvasrenderingcontext2d/getimagedata/index.html new file mode 100644 index 0000000000..c8b6bdf2be --- /dev/null +++ b/files/de/web/api/canvasrenderingcontext2d/getimagedata/index.html @@ -0,0 +1,142 @@ +--- +title: CanvasRenderingContext2D.getImageData() +slug: Web/API/CanvasRenderingContext2D/getImageData +translation_of: Web/API/CanvasRenderingContext2D/getImageData +--- +
{{APIRef}}
+ +

Die CanvasRenderingContext2D.getImageData() Methode der Canvas 2D API gibt ein Objekt des Types  {{domxref("ImageData")}} zurück. Dieses Objekt repräsentiert die jeweiligen Pixel-Daten im Bereich des Rechtecks mit den Startkoordinaten (sx,sy und den Dimensionen sw  in der Breite und sy  in der Höhe. 

+ +

Syntax

+ +
ImageData ctx.getImageData(sx, sy, sw, sh);
+
+ +

Parameters

+ +
+
sx
+
Die x Koordinate der oberen linken Ecke des Rechtecks, aus welchem die Pixel-Daten gelesen werden.
+
sy
+
Die y Koordinate der oberen linken Ecke des Rechtecks, aus welchem die Pixel-Daten gelesen werden.
+
sw
+
Die Breite des Rechtecks aus dem die Pixel-Daten gelesen werden.
+
sh
+
Die Höhe des Rechtecks aus dem die Pixel-Daten gelesen werden. 
+
+ +

Rückgabewerte

+ +

Ein Objekt vom Typ {{domxref("ImageData")}} das die Pixeldaten im angegeben bereich des Canvas-Elements beinhaltet.

+ +

Fehlertypen

+ +
+
IndexSizeError
+
Tritt ein, wenn entweder das Höhen oder das Breiten Argument null ist.
+
+ +

Beispiele

+ +

Benutzung der getImageData Funktion

+ +

Das ist ein einfaches Code-Beispiel zur Benutzung der getImageData Funktion. Für mehr Informationen siehe Pixel manipulation with canvas und die Referenz zum {{domxref("ImageData")}} Objekt.

+ +

HTML

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

JavaScript

+ +
var canvas = document.getElementById('canvas');
+var ctx = canvas.getContext('2d');
+ctx.rect(10, 10, 100, 100);
+ctx.fill();
+
+console.log(ctx.getImageData(50, 50, 100, 100));
+// ImageData { width: 100, height: 100, data: Uint8ClampedArray[40000] }
+
+ +

Specifications

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

Browser Kompatibilität

+ +

{{ CompatibilityTable}}

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

[1] Ab {{GeckoRelease("5.0")}} unterstützt getImageData() die Angabe von Rechtecken, die die Ränder des Canvas-Elements überschreiten. Die Pixel, die außerhalb des Elementes liegen, werden als transparentes Schwarz zurückgegeben. Auch wenn die größe des Rechtecks kleiner als eins ist wird jetzt mindestens ein Pixel als Pixel-Daten zurückgegeben.

+ +

Sehen Sie auch

+ + diff --git a/files/de/web/api/canvasrenderingcontext2d/index.html b/files/de/web/api/canvasrenderingcontext2d/index.html new file mode 100644 index 0000000000..aa9c1ea07a --- /dev/null +++ b/files/de/web/api/canvasrenderingcontext2d/index.html @@ -0,0 +1,432 @@ +--- +title: CanvasRenderingContext2D +slug: Web/API/CanvasRenderingContext2D +tags: + - API + - Canvas + - CanvasRenderingContext2D + - Graphics + - Image + - Shape +translation_of: Web/API/CanvasRenderingContext2D +--- +
{{APIRef}}
+ +

Das CanvasRenderingContext2D-Interface stellt den 2D-Renderkontext für die Zeichenoberfläche eines {{ HTMLElement("canvas") }} zur Verfügung. Es wird zum Zeichnen von Formen, Text, Bildern und anderen Objekten benutzt.

+ +

Eigenschaften und Methoden finden Sie in der Sidebar und weiter unten. Das Canvas-Tutorial bietet Ihnen außerdem weitere Informationen, Beispiele und Ressourcen.

+ +

Ein einfaches Beispiel

+ +

Um eine CanvasRenderingContext2D Instanz zu erhalten, muss man erst ein  HTML <canvas> Element haben, mit dem man arbeiten kann:

+ +
<canvas id="my-house" width="300" height="300"></canvas>
+ +

Um ein Objekt dieses Interfaces zu erhalten, benutzen Sie die Methode {{domxref("HTMLCanvasElement.getContext()", "getContext()")}} eines <canvas>, mit "2d" als Argument:

+ +
const canvas = document.getElementById('my-house');
+const ctx = canvas.getContext('2d');
+
+ +

Sobald Sie den Kontext der Zeichenoberfläche haben, können Sie darin zeichnen, was immer Sie möchten. Dieser Code zeichnet ein Haus:

+ +
// Die Lininestärke festlegen
+ctx.lineWidth = 10;
+
+// Wand
+ctx.strokeRect(75, 140, 150, 110);
+
+// Tür
+ctx.fillRect(130, 190, 40, 60);
+
+// Dach
+ctx.moveTo(50, 140);
+ctx.lineTo(150, 60);
+ctx.lineTo(250, 140);
+ctx.closePath();
+ctx.stroke();
+
+ +

Die enstandene Zeichnung sieht so aus:

+ +

{{EmbedLiveSample("Basic_example", 700, 330)}}

+ +

Referenz

+ +

Rechtecke zeichnen

+ +

Es gibt drei Methoden, die sofort Rechtecke innerhalb des Canvas zu zeichnen.

+ +
+
{{domxref("CanvasRenderingContext2D.clearRect()")}}
+
Setzt alle Pixel im Rechteck mit Startpunkt (x, y) und Größe (width, height) auf schwarz und transparent wodurch jeglicher vorheriger Inhalt gelöscht wird.
+
{{domxref("CanvasRenderingContext2D.fillRect()")}}
+
Zeichnet ein gefülltes Rechteck mit Startpunkt (x, y) und Größe (width, height).
+
{{domxref("CanvasRenderingContext2D.strokeRect()")}}
+
Zeichnet ein Rechteck mit Startpunkt (x, y) und Größe (width, height), verwendet dabei den aktuellem stroke style.
+
+ +

Text darstellen

+ +

Die folgenden Methoden zeichnen Text auf dem Canvas. Siehe auch das {{domxref("TextMetrics")}} - Objekt für die Texteigenschaften.

+ +
+
{{domxref("CanvasRenderingContext2D.fillText()")}}
+
Zeichnet einen gegebenen Text (gefüllt) an die gegebene Position (x, y).
+
{{domxref("CanvasRenderingContext2D.strokeText()")}}
+
Zeichnet einen gegebenen Text (Umrisse) an die gegebene Position (x, y).
+
{{domxref("CanvasRenderingContext2D.measureText()")}}
+
Gibt ein {{domxref("TextMetrics")}}-Objekt zurück.
+
+ +

Linienstile

+ +

Die folgenden Methoden und Eigenschaften beeinflussen die Art und Weise, wie Linien gezeichnet werden.

+ +
+
{{domxref("CanvasRenderingContext2D.lineWidth")}}
+
Linienbreite. Standard: 1.0
+
{{domxref("CanvasRenderingContext2D.lineCap")}}
+
Typ des Linienabschlusses. Mögliche Werte: butt (default), round, square.
+
{{domxref("CanvasRenderingContext2D.lineJoin")}}
+
Definiert den Typ der Ecken, wo sich zwei Linien treffen. Mögliche Werte: round, bevel, miter (default).
+
{{domxref("CanvasRenderingContext2D.miterLimit")}}
+
Verbindungsecken-Größe. Standard: 10.
+
{{domxref("CanvasRenderingContext2D.getLineDash()")}}
+
Gibt das aktuelle Linienstrich-Array zurück, welches eine gerade Anzahl positiver Zahlen enthält.
+
{{domxref("CanvasRenderingContext2D.setLineDash()")}}
+
Setzt das aktuelle Linienstrich-Array auf einen neuen Wert.
+
{{domxref("CanvasRenderingContext2D.lineDashOffset")}}
+
Spezifiziert, wo auf einer Linie ein Strich-Array beginnt.
+
+ +

Textstile

+ +

Die folgenden Eigenschaften bestimmen, wie Text dargestellt wird.

+ +
+
{{domxref("CanvasRenderingContext2D.font")}}
+
Font-Einstellung. Standard: 10px sans-serif
+
{{domxref("CanvasRenderingContext2D.textAlign")}}
+
Ausrichtungs-Einstellung. Mögliche Werte: start (default), end, left, right oder center.
+
{{domxref("CanvasRenderingContext2D.textBaseline")}}
+
Ausrichtungseinstellung zur Basislinie. Mögliche Werte: top, hanging, middle, alphabetic (default), ideographic, bottom.
+
{{domxref("CanvasRenderingContext2D.direction")}}
+
Direktionalität. Mögliche Werte: ltr, rtl, inherit (default).
+
+ +

Füll- und Linienfarbe

+ +

Die Füllfarbe (fillStyle) wird innerhalb von Formen angewendet, die Linienfarbe (strokeStyle) auf die Randlinie von Formen. Beides kann statt einer Farbe auch ein Farbverlauf oder ein Muster sein.

+ +
+
{{domxref("CanvasRenderingContext2D.fillStyle")}}
+
Farbe oder Stil für innerhalb von Formen. Standardwert #000 (schwarz).
+
{{domxref("CanvasRenderingContext2D.strokeStyle")}}
+
Farbe oder Stil für die Randlinie von Formen. Standardwert #000 (schwarz).
+
+ +

Farbverläufe und Muster

+ +
+
{{domxref("CanvasRenderingContext2D.createLinearGradient()")}}
+
Erzeugt einen linearen Farbverlauf entlang der Linie gegeben durch die Koordinaten, die als Parameter übergeben werden.
+
{{domxref("CanvasRenderingContext2D.createRadialGradient()")}}
+
Erzeugt einen radialen (kreisförmigen) Farbverlauf entlang der Linie gegeben durch die Koordinaten, die als Parameter übergeben werden.
+
{{domxref("CanvasRenderingContext2D.createPattern()")}}
+
Erzeugt ein Muster aus dem angegebenen Bild (ein {{domxref("CanvasImageSource")}}). Es wiederholt das Bild in den Richtungen, die mit dem repetition Parameter definiert werden. Diese Methode gibt ein {{domxref("CanvasPattern")}} zurück.
+
+ +

Schatten

+ +
+
{{domxref("CanvasRenderingContext2D.shadowBlur")}}
+
Definiert den Unschärfe-Effekt. Standardwert 0
+
{{domxref("CanvasRenderingContext2D.shadowColor")}}
+
Farbe des Schattens. Standardwert: komplett transparentes Schwarz.
+
{{domxref("CanvasRenderingContext2D.shadowOffsetX")}}
+
Horizontale Entfernung des Schattens. Standardwert 0.
+
{{domxref("CanvasRenderingContext2D.shadowOffsetY")}}
+
Vertikale Entfernung des Schattens. Standardwert 0.
+
+ +

Pfade

+ +

Die folgende Methoden können verwendet werden, um Pfade von Objekten zu manipulieren.

+ +
+
{{domxref("CanvasRenderingContext2D.beginPath()")}}
+
Startet einen neuen Pfad, indem die Liste mit allen Unterpfaden geleert wird. Rufe diese Methode auf, wenn du einen neuen Pfad starten willst.
+
{{domxref("CanvasRenderingContext2D.closePath()")}}
+
Sorgt dafür, dass die Stiftspitze zum Start des aktuellen Unterpfades zurückwandert. Es wird versucht eine greade Linie von der aktuellen Position zum Beginn der Linie zu zeichen. Wenn die Form schon geschlossen wurde oder nur einen Punkt enthält, macht diese Funktion nichts.
+
{{domxref("CanvasRenderingContext2D.moveTo()")}}
+
Bewegt den Anfangspunkt für einen neuen Unterpfad zu den übergebenen (x, y) Koordinaten.
+
{{domxref("CanvasRenderingContext2D.lineTo()")}}
+
Verbindet den letzten Punkt im Unterpfad mit den übergebenen (x, y) Koordinaten in einer geraden Linie.
+
{{domxref("CanvasRenderingContext2D.bezierCurveTo()")}}
+
Fügt eine kubische Bézierkurve zum Pfad hinzu. Diese benötigt drei Punkte. Die ersten zwei sind Kontrollpunkte für die Krümmung, der dritte ist das Ende der Kurve. Die Kurve beginnt am letzten Punkt im aktuellen Pfad, dieser kann davor mit moveTo() geändert werden.
+
{{domxref("CanvasRenderingContext2D.quadraticCurveTo()")}}
+
Fügt eine quadratische Bézierkurve zum aktuellen Pfad hinzu.
+
{{domxref("CanvasRenderingContext2D.arc()")}}
+
Fügt einen Kreisbogen zum Pfad hinzu, mit Kreismittelpunkt (x, y) und Radius r. Der Startwinkel ist startAngle, der Endwinkel endAngle, Richtung gegen den Uhrzeigersinn.
+
{{domxref("CanvasRenderingContext2D.arcTo()")}}
+
Fügt einen Kreisbogen zum Pfad mit den gegebenen Kontrollpunkten und Radius hinzu, verbunden mit dem letzten Punkt im Pfad durch eine gerade Linie.
+
{{domxref("CanvasRenderingContext2D.ellipse()")}} {{experimental_inline}}
+
Fügt eine Ellipse zum Pfad hinzu, mit dem Zentrum (x, y) und den Radien radiusX und radiusY, beginnend bei startAngle und endend bei endAngle, Richtung gegen den Uhrzeigersinn.
+
{{domxref("CanvasRenderingContext2D.rect()")}}
+
Erzeugt einen Pfad mit einem Rechteck an der Position (x, y) und den Dimensionen width und height.
+
+ +

Pfade zeichnen

+ +
+
{{domxref("CanvasRenderingContext2D.fill()")}}
+
Füllt den Unterpfad mit der aktuellen Füllfarbe (bzw. Farbverlauf, Muster).
+
{{domxref("CanvasRenderingContext2D.stroke()")}}
+
Zeichnet die Linien des Unterpfades mit der aktuellen Linienfarbe (bzw. Farbverlauf, Muster).
+
{{domxref("CanvasRenderingContext2D.drawFocusIfNeeded()")}}
+
Wenn ein gegebenes Element fokussiert wird, zeichnet diese Methode einen Fokusring um den aktuellen Pfad.
+
{{domxref("CanvasRenderingContext2D.scrollPathIntoView()")}}
+
Scrollt den aktuellen Pfad oder einen bestimmten Pfad in Sicht.
+
{{domxref("CanvasRenderingContext2D.clip()")}}
+
Erzeugt einen zugeschnittenen Pfad aus den aktuellen Unterpfaden. Alles, was nach clip() gezeichnet wird, erscheint nur im zugeschnittenen Pfad. Für ein Beispiel, siehe  Clipping paths im Canvas Tutorial.
+
{{domxref("CanvasRenderingContext2D.isPointInPath()")}}
+
Gibt zurück, ob der angegebene Punkt im aktuellen Pfad enthalten ist oder nicht.
+
{{domxref("CanvasRenderingContext2D.isPointInStroke()")}}
+
Gibt zurück, ob der angegebene Punkt innerhalb des bemalten Bereichs im Pfad ist oder nicht.
+
+ +

Transformationen

+ +

Objekte im CanvasRenderingContext2D-Renderkontext haben eine aktuelle Transformationsmatrix und Methoden, um diese zu manipulieren. Die Transformationsmatrix wird angewendet, wenn der aktuelle Pfad erzeugt wird und wenn Text, Formen oder {{domxref("Path2D")}} Objekte gemalt werden. Folgende Methoden sind hier für historische und Kompatibilitätszwecke aufgelistet, da heutzutage meistens {{domxref("SVGMatrix")}} Objekte verwendet werden und in Zukunft diese Methoden ersetzen werden.

+ +
+
{{domxref("CanvasRenderingContext2D.currentTransform")}} {{experimental_inline}}
+
Die momentane Transformationsmatrix ({{domxref("SVGMatrix")}} object).
+
{{domxref("CanvasRenderingContext2D.rotate()")}}
+
Fügt eine Drehung zur Transformationsmatrix hinzu. Der angle-Parameter stellt einen Drehwinkel im Uhrzeigersinn dar und wird in radians ausgedrückt.
+
{{domxref("CanvasRenderingContext2D.scale()")}}
+
Fügt eine skalierende Transformation zu den Längeneinheiten des canvas hinzu (horizontal um Faktor x, vertikal um Faktor y). Was nach scale() auf das canvas gezeichnet wird, wird also dementsprechend gestaucht oder gestreckt.
+
{{domxref("CanvasRenderingContext2D.translate()")}}
+
Fügt eine übersetzende Transformation hinzu, die die Position des canvas relativ zu seinem Koordinatensystem verschiebt (horizontal um x, vertikal um y). Was nach translate() gezeichnet wird, ist also um (x, y) verschoben.
+
{{domxref("CanvasRenderingContext2D.transform()")}}
+
Multipliziert die aktuelle Transformationsmatrix mit der Matrix, die durch die Parameter dieser Funktion beschrieben wird.
+
{{domxref("CanvasRenderingContext2D.setTransform()")}}
+
Setzt die aktuellen Transformationen zurück und ruft dann die transform() Methode mit den selben Parametern auf.
+
{{domxref("CanvasRenderingContext2D.resetTransform()")}} {{experimental_inline}}
+
Setzt die aktuellen Transformationen zurück.
+
+ +

Compositing

+ +
+
{{domxref("CanvasRenderingContext2D.globalAlpha")}}
+
Alpha-Wert bzw. Deckkraft, die auf alle Formen und Bilder angewendet wird, bevor diese auf dem canvas gezeichnet werden. Standardwert 1.0 (undurchsichtig).
+
{{domxref("CanvasRenderingContext2D.globalCompositeOperation")}}
+
Zusammen mit globalAlpha legt dieser Wert fest, wie Formen und Bilder abhängig vom Hintergrund auf das canvas gezeichnet werden sollen.
+
+ +

Bilder zeichnen

+ +
+
{{domxref("CanvasRenderingContext2D.drawImage()")}}
+
Zeichnet das übergebene Bild. Diese Methode ist in diversen Formaten verfügbar, wodurch sie große Flexibilität in der Nutzung bietet.
+
+ +

Pixelmanipulation

+ +

Siehe auch das {{domxref("ImageData")}} Objekt.

+ +
+
{{domxref("CanvasRenderingContext2D.createImageData()")}}
+
Erzeugt ein neues, leeres {{domxref("ImageData")}} Objekt mit den angegebenen Dimensionen. Alle Pixel in diesem Objekt sind transparent schwarz.
+
{{domxref("CanvasRenderingContext2D.getImageData()")}}
+
Gibt ein {{domxref("ImageData")}} Objekt zurück, das die dem canvas zugrunde liegenden Pixeldaten enthält. Die Methode wird auf einen bestimmten Ausschnitt des canvas angewendet, beginnend bei (sx, sy), mit Breite sw und Höhe sh.
+
{{domxref("CanvasRenderingContext2D.putImageData()")}}
+
Malt Pixeldaten des {{domxref("ImageData")}} Objekts auf das canvas. Wenn ein dreckiges Rechteck angegeben wird, werden nur die Pixel dieses Rechtecks gemalt.
+
+ +

Bildglättung

+ +
+
{{domxref("CanvasRenderingContext2D.imageSmoothingEnabled")}} {{experimental_inline}}
+
Bildglättungsmodus; wenn deaktiviert, werden Bilder beim Skalieren nicht geglättet.
+
+ +

Der Leinwand-Zustand

+ +

Der CanvasRenderingContext2D-Renderkontext enthält eine Vielzahl an Zeichnungszuständen (Attribute für Linienstile, Füllstile, Schattenstile, Textstile). Die folgenden Methoden helfen Ihnen mit diesen Zuständen zu arbeiten:

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

Trefferregionen

+ +
+
{{domxref("CanvasRenderingContext2D.addHitRegion()")}} {{experimental_inline}}
+
Fügt eine Trefferregion (hit region) zur Leinwand hinzu.
+
{{domxref("CanvasRenderingContext2D.removeHitRegion()")}} {{experimental_inline}}
+
Entfernt eine Trefferregion mit gegebener id von der Leinwand.
+
{{domxref("CanvasRenderingContext2D.clearHitRegions()")}} {{experimental_inline}}
+
Entfernt alle Trefferregionen von der Leinwand.
+
+ +

Filter

+ +
+
{{experimental_inline}} {{domxref("CanvasRenderingContext2D.filter")}}
+
Applies a CSS or SVG filter to the canvas, e.g., to change its brightness or bluriness.
+
+ +

Unstandardisierte APIs

+ + + +

Die meisten dieser APIs sind veraltet und wurden kurz nach Chrome 36 entfernt.

+ +
+
{{non-standard_inline}} {{obsolete_inline}} CanvasRenderingContext2D.clearShadow()
+
Entfernt alle Schatteneinstellungen wie  {{domxref("CanvasRenderingContext2D.shadowColor")}} und {{domxref("CanvasRenderingContext2D.shadowBlur")}}.
+
{{non-standard_inline}} {{obsolete_inline}} CanvasRenderingContext2D.drawImageFromRect()
+
Das ist redundant zum equivalenten Überladung von  drawImage.
+
{{non-standard_inline}} {{obsolete_inline}} CanvasRenderingContext2D.setAlpha()
+
Verwenden Sie {{domxref("CanvasRenderingContext2D.globalAlpha")}} anstelle dieser Methode.
+
{{non-standard_inline}} {{obsolete_inline}} CanvasRenderingContext2D.setCompositeOperation()
+
Verwenden Sie {{domxref("CanvasRenderingContext2D.globalCompositeOperation")}} anstelle dieser Methode.
+
{{non-standard_inline}} {{obsolete_inline}} CanvasRenderingContext2D.setLineWidth()
+
Verwenden Sie {{domxref("CanvasRenderingContext2D.lineWidth")}} anstelle dieser Methode.
+
{{non-standard_inline}} {{obsolete_inline}} CanvasRenderingContext2D.setLineJoin()
+
Verwenden Sie {{domxref("CanvasRenderingContext2D.lineJoin")}} anstelle dieser Methode.
+
{{non-standard_inline}} {{obsolete_inline}} CanvasRenderingContext2D.setLineCap()
+
Verwenden Sie {{domxref("CanvasRenderingContext2D.lineCap")}} anstelle dieser Methode.
+
{{non-standard_inline}} {{obsolete_inline}} CanvasRenderingContext2D.setMiterLimit()
+
Verwenden Sie {{domxref("CanvasRenderingContext2D.miterLimit")}} anstelle dieser Methode.
+
{{non-standard_inline}} {{obsolete_inline}} CanvasRenderingContext2D.setStrokeColor()
+
Verwenden Sie {{domxref("CanvasRenderingContext2D.strokeStyle")}} anstelle dieser Methode.
+
{{non-standard_inline}} {{obsolete_inline}} CanvasRenderingContext2D.setFillColor()
+
Verwenden Sie {{domxref("CanvasRenderingContext2D.fillStyle")}} anstelle dieser Methode.
+
{{non-standard_inline}} {{obsolete_inline}} CanvasRenderingContext2D.setShadow()
+
Verwenden Sie {{domxref("CanvasRenderingContext2D.shadowColor")}} und {{domxref("CanvasRenderingContext2D.shadowBlur")}} anstelle dieser Methode.
+
{{non-standard_inline}} {{obsolete_inline}} CanvasRenderingContext2D.webkitLineDash
+
Verwenden Sie {{domxref("CanvasRenderingContext2D.getLineDash()")}} und {{domxref("CanvasRenderingContext2D.setLineDash()")}} anstelle dieser Methode.
+
{{non-standard_inline}} {{obsolete_inline}} CanvasRenderingContext2D.webkitLineDashOffset
+
Verwenden Sie {{domxref("CanvasRenderingContext2D.lineDashOffset")}} anstelle dieser Methode.
+
{{non-standard_inline}} {{obsolete_inline}} CanvasRenderingContext2D.webkitImageSmoothingEnabled
+
Verwenden Sie {{domxref("CanvasRenderingContext2D.imageSmoothingEnabled")}} anstelle dieser Methode.
+
+ + + +
+
{{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).
+
+ +

Specifications

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

Browser compatibility

+ +
+ + +

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

+
+ + + +

See also

+ + diff --git a/files/de/web/api/canvasrenderingcontext2d/ispointinpath/index.html b/files/de/web/api/canvasrenderingcontext2d/ispointinpath/index.html new file mode 100644 index 0000000000..5eac7321fe --- /dev/null +++ b/files/de/web/api/canvasrenderingcontext2d/ispointinpath/index.html @@ -0,0 +1,206 @@ +--- +title: CanvasRenderingContext2D.isPointInPath() +slug: Web/API/CanvasRenderingContext2D/isPointInPath +translation_of: Web/API/CanvasRenderingContext2D/isPointInPath +--- +
{{APIRef}}
+ +

Die Methode CanvasRenderingContext2D.isPointInPath() der Canvas 2D API entscheidet darüber, ob ein Punkt in einem gegeben Pfad enthalten ist.

+ +

Syntax

+ +
boolean ctx.isPointInPath(x, y);
+boolean ctx.isPointInPath(x, y, fillRule);
+
+boolean ctx.isPointInPath(path, x, y);
+boolean ctx.isPointInPath(path, x, y, fillRule);
+
+ +

Parameter

+ +
+
x
+
Die X-Koordinate des zu prüfenden Punktes.
+
y
+
Die Y-Koordinate des zu prüfenden Punktes.
+
fillRule
+
Der Algorithmus, der prüft, ob der Punkt innerhalb oder außerhalb des Pfades liegt.
+ Mögliche Werte: + +
+
path
+
Ein {{domxref("Path2D")}} Objekt.
+
+ +

Rückgabewert

+ +
+
{{jsxref("Boolean")}}
+
Ein Boolean, welcher true ist, wenn der gegebene Punkt innerhalb des gegeben Pfades liegt, ansonsten false.
+
+ +

Beispiele

+ +

Benutzung der Methode isPointInPath

+ +

Dies ist ein einfaches Snippet, welches die isPointinPath Methode nutzt, um zu prüfen, ob ein Punkt in gegebenem Pfad enthalten ist.

+ +

HTML

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

JavaScript

+ +
var canvas = document.getElementById("canvas");
+var ctx = canvas.getContext("2d");
+
+ctx.rect(10, 10, 100, 100);
+ctx.stroke();
+console.log(ctx.isPointInPath(10, 10)); // true
+
+ +

Editieren Sie den folgenden Quelltext. Die Änderungen werden in Echtzeit übernommen und Log-Ausgaben in die console ausgegeben:

+ +
+
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();
+console.log(ctx.isPointInPath(10, 10)); // true</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) }}

+ +

Specifications

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

Browser compatibility

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
Path parameter{{ CompatVersionUnknown() }}{{ CompatGeckoDesktop(31) }}{{ CompatNo }}{{ CompatVersionUnknown() }}{{ CompatNo }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
Path parameter{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatGeckoMobile(31) }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +

Compatibility notes

+ + + +

See also

+ + diff --git a/files/de/web/api/canvasrenderingcontext2d/scale/index.html b/files/de/web/api/canvasrenderingcontext2d/scale/index.html new file mode 100644 index 0000000000..b26824a51e --- /dev/null +++ b/files/de/web/api/canvasrenderingcontext2d/scale/index.html @@ -0,0 +1,223 @@ +--- +title: CanvasRenderingContext2D.scale() +slug: Web/API/CanvasRenderingContext2D/scale +tags: + - API + - Canvas + - CanvasRenderingContext2D + - Méthode + - Referenz +translation_of: Web/API/CanvasRenderingContext2D/scale +--- +
{{APIRef}}
+ +

Die Methode CanvasRenderingContext2D.scale() der Canvas 2D API skaliert das Canvas-Element um den Faktor x horizontal und um den Faktor y vertikal.

+ +

Normalerweise ist eine Einheit auf dem Canvas genau ein Pixel. Wenn wir zum Beispiel einen Skalierungsfaktor von 0,5 Pixeln anwenden, ist eine Einheit 0,5 Pixel und alle Objekte werden mit der halben Größe gezeichnet. Analog dazu vergößert der Skalierungsfaktor 2,0 die Längeneinheit auf zwei Pixel. Die Objekte werden dann doppelt so groß gezeichnet.

+ +

Syntax

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

Parameter

+ +
+
x
+
Skalierungsfaktor in horizontaler Richtung.
+
y
+
Skalierungsfaktor in vertikaler Richtung
+
+ +

Beispiele

+ +

Die Methode scale verwenden

+ +

Dies ist nur ein kurzes Beispiel, das die Methode scale benutzt.

+ +

HTML

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

JavaScript

+ +
var canvas = document.getElementById('canvas');
+var ctx = canvas.getContext('2d');
+
+ctx.scale(10, 3);
+ctx.fillRect(10, 10, 10, 10);
+
+// reset current transformation matrix to the identity matrix
+ctx.setTransform(1, 0, 0, 1, 0, 0);
+
+ +

Editieren Sie den folgenden Code und sehen Sie die Änderungen sofort im 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.scale(10, 3);
+ctx.fillRect(10,10,10,10);
+ctx.setTransform(1, 0, 0, 1, 0, 0);</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) }}

+ +

scale verwenden, um horizontal oder vertikal zu spiegeln

+ +

Sie können ctx.scale(-1, 1) benutzen, um den Inhalt horizontal zu spiegeln und ctx.scale(1, -1), um ihn vertikal zu spiegeln.

+ +
+
Playable code2
+ +
<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.scale(-1, 1);
+ctx.font = "48px serif";
+ctx.fillText("Hello world!", -320, 120);
+ctx.setTransform(1, 0, 0, 1, 0, 0);</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_code2', 700, 360) }}

+ +

Spezifikationen

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

Browserkompabilität

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Grundlegende Unterstützung{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Grundlegende Unterstützung{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +

Siehe auch

+ + diff --git a/files/de/web/api/canvasrenderingcontext2d/setlinedash/index.html b/files/de/web/api/canvasrenderingcontext2d/setlinedash/index.html new file mode 100644 index 0000000000..a7d5bd82c3 --- /dev/null +++ b/files/de/web/api/canvasrenderingcontext2d/setlinedash/index.html @@ -0,0 +1,179 @@ +--- +title: CanvasRenderingContext2D.setLineDash() +slug: Web/API/CanvasRenderingContext2D/setLineDash +translation_of: Web/API/CanvasRenderingContext2D/setLineDash +--- +
{{APIRef}}
+ +

The CanvasRenderingContext2D.setLineDash() method of the Canvas 2D API sets the line dash pattern.

+ +

Syntax

+ +
void ctx.setLineDash(segments);
+
+ +

Parameters

+ +
+
segments
+
An {{jsxref("Array")}}. A list of numbers that specifies distances to alternately draw a line and a gap (in coordinate space units). If the number of elements in the array is odd, the elements of the array get copied and concatenated. For example, [5, 15, 25] will become [5, 15, 25, 5, 15, 25]. An empty array clears the dashes, so that a solid line will be drawn.
+
+ +

Examples

+ +

Using the setLineDash method

+ +

This is just a simple code snippet which uses the setLineDash method to draw a dashed line.

+ +

HTML

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

JavaScript

+ +
var canvas = document.getElementById("canvas");
+var ctx = canvas.getContext("2d");
+
+ctx.setLineDash([5, 15]);
+
+ctx.beginPath();
+ctx.moveTo(0,100);
+ctx.lineTo(400, 100);
+ctx.stroke();
+
+ +

Edit the code below and see your changes update live in the 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.setLineDash([5, 15]);
+ctx.beginPath();
+ctx.moveTo(0,100);
+ctx.lineTo(400, 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) }}

+ +

Specifications

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

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{ CompatGeckoDesktop(27) }}{{ CompatIE(11) }}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{ CompatGeckoMobile(27) }}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Gecko-specific notes

+ + + +

WebKit-specific notes

+ + + +

See also

+ + diff --git a/files/de/web/api/canvasrenderingcontext2d/textalign/index.html b/files/de/web/api/canvasrenderingcontext2d/textalign/index.html new file mode 100644 index 0000000000..1f1651f456 --- /dev/null +++ b/files/de/web/api/canvasrenderingcontext2d/textalign/index.html @@ -0,0 +1,128 @@ +--- +title: CanvasRenderingContext2D.textAlign +slug: Web/API/CanvasRenderingContext2D/textAlign +translation_of: Web/API/CanvasRenderingContext2D/textAlign +--- +
{{APIRef}}
+ +

Die CanvasRenderingContext2D.textAlign Eigenschaft der Canvas 2D API spezifiert die aktuelle Textausrichtung welche beim zeichnen von Text verwendet wird.

+ +

Nehmen Sie in Acht, dass die Ausrichtung auf dem x Wert der {{domxref("CanvasRenderingContext2D.fillText", "fillText()")}} Methode basiert. Wenn textAlign  "center" ist,  dann würde der Text an der Stelle x - (width / 2) gezeichnet werden.

+ +

Syntax

+ +
ctx.textAlign = "left" || "right" || "center" || "start" || "end";
+
+ +

Optionen

+ +

Mögliche Werte:

+ +
+
left
+
Der Text wird linksbündig ausgerichtet.
+
right
+
Der Text wird rechtsbündig ausgerichtet.
+
center
+
Der Text wird zentiert ausgerichtet.
+
start
+
Der Text wird am normalen Start der Zeile ausgerichtet. (Links -oder rechtsbündig, je nach Sprache).
+
end
+
Der Text wird am normalen Ende der Zeile ausgerichtet (Links -oder rechtsbündig, je nach Sprache).
+
+ +

Der Standardwert ist start.

+ +

Beispiele

+ +

Benutzung der textAlign Eigenschaft

+ +

Ein einfaches Beispiel welches die textAlign Eigenschaft benutzt um die Textausrichtung zu ändern.

+ +

HTML

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

JavaScript

+ +
var canvas = document.getElementById('canvas');
+var ctx = canvas.getContext('2d');
+
+ctx.font = '48px serif';
+ctx.textAlign = 'left';
+ctx.strokeText('Hello world', 0, 100);
+
+ +

Ändern Sie den Code um Ihre Änderungen im Canvas zu sehen:

+ + + +

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

+ +

Spezifikationen

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

Browserkompatibilität

+ + + +

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

+ +

Siehe auch

+ + diff --git a/files/de/web/api/childnode/index.html b/files/de/web/api/childnode/index.html new file mode 100644 index 0000000000..07dcc1cb33 --- /dev/null +++ b/files/de/web/api/childnode/index.html @@ -0,0 +1,190 @@ +--- +title: ChildNode +slug: Web/API/ChildNode +tags: + - API + - DOM + - Experimental + - Interface + - NeedsTranslation + - Node + - TopicStub +translation_of: Web/API/ChildNode +--- +
{{APIRef("DOM")}}
+ +

The ChildNode interface contains methods that are particular to {{domxref("Node")}} objects that can have a parent.

+ +

ChildNode is a raw interface and no object of this type can be created; it is implemented by {{domxref("Element")}}, {{domxref("DocumentType")}}, and {{domxref("CharacterData")}} objects.

+ +

Properties

+ +

There are neither inherited, nor specific properties.

+ +

Methods

+ +

There are no inherited methods.

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

Specifications

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

+ +

Browser compatibility

+ +

{{ CompatibilityTable }}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support (on {{domxref("Element")}}){{CompatChrome(1.0)}}{{CompatVersionUnknown}}{{CompatGeckoDesktop(23)}}9.010.04.0
Support on {{domxref("DocumentType")}} and {{domxref("CharacterData")}} {{experimental_inline}}{{CompatChrome(23.0)}}{{CompatNo}}{{CompatGeckoDesktop(23)}}{{CompatNo}}16.0{{CompatNo}}
remove(){{experimental_inline}}{{CompatChrome(29.0)}}{{CompatVersionUnknown}}{{CompatGeckoDesktop(23)}}{{CompatNo}}16.0{{CompatNo}}
before(), after(), and replaceWith() {{experimental_inline}}{{CompatChrome(54.0)}}{{CompatNo}}{{CompatGeckoDesktop(49)}}{{CompatNo}}{{CompatOpera(39)}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
Basic support (on {{domxref("Element")}}){{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile(23)}}{{CompatVersionUnknown}}10.0{{CompatVersionUnknown}}{{CompatVersionUnknown}}
Support on {{domxref("DocumentType")}} and {{domxref("CharacterData")}} {{experimental_inline}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatGeckoMobile(23)}}{{CompatNo}}16.0{{CompatNo}}{{CompatVersionUnknown}}
remove(){{experimental_inline}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile(23)}}{{CompatNo}}16.0{{CompatNo}}{{CompatVersionUnknown}}
before(), after(), and replaceWith() {{experimental_inline}}{{CompatNo}}{{CompatChrome(54.0)}}{{CompatNo}}{{CompatGeckoMobile(49)}}{{CompatNo}}{{CompatOperaMobile(39)}}{{CompatNo}}{{CompatChrome(54.0)}}
+
+ +

See also

+ + diff --git a/files/de/web/api/childnode/remove/index.html b/files/de/web/api/childnode/remove/index.html new file mode 100644 index 0000000000..bae33f75c0 --- /dev/null +++ b/files/de/web/api/childnode/remove/index.html @@ -0,0 +1,97 @@ +--- +title: ChildNode.remove() +slug: Web/API/ChildNode/remove +tags: + - API + - ChildNode + - DOM + - Experimentell + - Méthode +translation_of: Web/API/ChildNode/remove +--- +
{{APIRef("DOM")}}
+ +

Die ChildNode.remove() Methode entfernt ein Objekt aus der Baumstruktur ("tree") zu der es gehört.

+ +

Syntax

+ +
node.remove();
+
+ +

Beispiel

+ +

Benutzung von remove()

+ +
<div id="div-01">Dies ist div-01</div>
+<div id="div-02">Dies ist div-02</div>
+<div id="div-03">Dies ist div-03</div>
+
+ +
var el = document.getElementById('div-02');
+el.remove(); // Entfernt das div Element mit der id 'div-02'
+
+ +

ChildNode.remove() kann nicht gescopet werden

+ +

Die remove() Methode kann nicht mit dem with Statement gescopet werden. {{jsxref("Symbol.unscopables")}} enthält mehr Informationen darüber.

+ +
with(node) {
+  remove();
+}
+// Erzeught einen ReferenceError
+ +

Polyfill

+ +

Ein Polyfill der remove() Methode in Internet Explorer 9 und höher sieht folgendermaßen aus:

+ +
// von:https://github.com/jserz/js_piece/blob/master/DOM/ChildNode/remove()/remove().md
+(function (arr) {
+  arr.forEach(function (item) {
+    if (item.hasOwnProperty('remove')) {
+      return;
+    }
+    Object.defineProperty(item, 'remove', {
+      configurable: true,
+      enumerable: true,
+      writable: true,
+      value: function remove() {
+        if (this.parentNode !== null)
+          this.parentNode.removeChild(this);
+      }
+    });
+  });
+})([Element.prototype, CharacterData.prototype, DocumentType.prototype]);
+ +

Specifikationen

+ + + + + + + + + + + + + + +
SpecifikationStatusKommentar
{{SpecName('DOM WHATWG', '#dom-childnode-remove', 'ChildNode.remove')}}{{Spec2('DOM WHATWG')}}Erste Definition.
+ +

Browser compatibility

+ +
+ + +

{{Compat("api.ChildNode.remove")}}

+
+ +

Siehe auch

+ + diff --git a/files/de/web/api/console/assert/index.html b/files/de/web/api/console/assert/index.html new file mode 100644 index 0000000000..834e253ce5 --- /dev/null +++ b/files/de/web/api/console/assert/index.html @@ -0,0 +1,98 @@ +--- +title: Console.assert() +slug: Web/API/Console/assert +translation_of: Web/API/console/assert +--- +
{{APIRef("Console API")}}
+ +

Schreibt eine Fehlermeldung in die Konsole, wenn eine Behauptung falsch ist. Wenn die Behauptung wahr ist, passiert nichts.

+ +

{{AvailableInWorkers}}

+ +

Die Methode console.assert() wurde in älteren Node.js Versionen anders implementiert als in Browsern. In Browsern wird durch den Aufruf von console.assert() mit einer falschen Behauptung message in die Konsole ausgegeben, ohne die Ausführung des nachfolgenden Codes zu unterbrechen. Vor Node.js v10.0.0 bewirkt eine falsche Behauptung jedoch auch, dass ein AssertionError ausgelöst wird. Diese Diskrepanz wurde mit Node v10 behoben, so dass console.assert() jetzt sowohl in Node als auch im Browser gleich funktioniert.

+ +

Syntax

+ +
console.assert(assertion, obj1 [, obj2, ..., objN]);
+console.assert(assertion, msg [, subst1, ..., substN]); // c-ähnliche Formatierung
+
+ +

Parameter

+ +
+
assertion
+
Jeder boolesche Ausdruck. Wenn die Behauptung falsch ist, wird message in der Console ausgegeben.
+
obj1 ... objN
+
Eine Liste der auszugebenden JavaScript-Objekte. Die String-Darstellungen jedes dieser Objekte werden in der angegebenen Reihenfolge zusammengefügt und ausgegeben.
+
msg
+
Ein JavaScript-String, der keine oder mehrere Ersetzungsstrings enthält.
+
subst1 ... substN
+
JavaScript-Objekte, mit denen Ersetzungsstrings in msg ersetzt werden sollen. Dieser Parameter gibt Ihnen zusätzliche Kontrolle über das Format der Ausgabe.
+
+ +

Beispiele

+ +

Im folgenden Codebeispiel wird die Verwendung eines JavaScript-Objekts nach der Behauptung veranschaulicht:

+ +
const errorMsg = 'the # is not even';
+for (let number = 2; number <= 5; number += 1) {
+    console.log('the # is ' + number);
+    console.assert(number % 2 === 0, {number: number, errorMsg: errorMsg});
+    // oder mit ES2015 Object Property Shorthand:
+    // console.assert(number % 2 === 0, {number, errorMsg});
+}
+// Ausgabe:
+// the # is 2
+// the # is 3
+// Assertion failed: {number: 3, errorMsg: "the # is not even"}
+// the # is 4
+// the # is 5
+// Assertion failed: {number: 5, errorMsg: "the # is not even"}
+ +

Beachten Sie, dass ein String, der einen Ersatzstring enthält, als Parameter für console.log() in Node und vielen, wenn nicht allen Browsern, funktioniert...

+ +
console.log('the word is %s', 'foo');
+// Ausgabe: the word is foo
+ +

...die Verwendung eines solchen Strings als Parameter für console.assert() jedoch derzeit nicht in allen Browsern wie erwartet funktioniert:

+ +
console.assert(false, 'the word is %s', 'foo');
+// korrekte Ausgabe in Node (e.g. v8.10.0) und einigen Browsern
+//     (z. B. Firefox v60.0.2):
+// Assertion failed: the word is foo
+// inkorrekte Ausgabe in einigen Browsern
+//     (z. B. Chrome v67.0.3396.87):
+// Assertion failed: the word is %s foo
+ +

Weitere Informationen finden Sie in der Dokumentation von {{domxref("console")}} unter Text in der Konsole ausgeben.

+ +

Spezifikationen

+ + + + + + + + + + + + + + + + +
SpezifikationStatusKommentar
{{SpecName("Console API", "#assert", "console.assert()")}}{{Spec2("Console API")}}Initiale Definition
+ +

Browserkompatibilität

+ +

{{Compat("api.Console.assert")}}

+ +

Siehe auch

+ + diff --git a/files/de/web/api/console/clear/index.html b/files/de/web/api/console/clear/index.html new file mode 100644 index 0000000000..3ff370c14b --- /dev/null +++ b/files/de/web/api/console/clear/index.html @@ -0,0 +1,49 @@ +--- +title: Console.clear() +slug: Web/API/Console/clear +translation_of: Web/API/Console/clear +--- +
{{APIRef("Console API")}}
+ +

Leert die Konsole.

+ +

Der Inhalt der Konsole wird mit einer informativen Nachricht wie "Konsole wurde geleert" ersetzt.

+ +

Beachten Sie, dass der Aufruf console.clear() in Google Chrome keine Wirkung hat, wenn der Benutzer in den Einstellungen die Option "Log bei Navigation nicht leeren" aktiviert hat.

+ +

Syntax

+ +
console.clear();
+
+ +

Spezifikationen

+ + + + + + + + + + + + + + + + +
SpezifikationStatusKommentar
{{SpecName("Console API", "#clear", "console.clear()")}}{{Spec2("Console API")}}Initiale Definition
+ +

Browserkompatibilität

+ + + +

{{Compat("api.Console.clear")}}

+ +

Siehe auch

+ + diff --git a/files/de/web/api/console/count/index.html b/files/de/web/api/console/count/index.html new file mode 100644 index 0000000000..4fdcf42299 --- /dev/null +++ b/files/de/web/api/console/count/index.html @@ -0,0 +1,103 @@ +--- +title: Console.count() +slug: Web/API/Console/count +translation_of: Web/API/Console/count +--- +
{{APIRef("Console API")}}
+ +

Die Methode count() protokolliert, wie oft sie an einer Stelle oder mit einem Bezeichner aufgerufen wurde. Sie nimmt ein optionales Argument label entgegen.

+ +

{{AvailableInWorkers}}

+ +

Syntax

+ +
console.count([label]);
+
+ +

Parameter

+ +
+
label {{optional_inline}}
+
Ein {{jsxref("String")}}. Wenn angegeben, gibt count() die Anzahl der Aufrufe mit diesem Label aus, ansonsten mit der Bezeichnung "default".
+
+ +

Beispiele

+ +

Nehmen wir folgenden Code als Beispiel:

+ +
let user = "";
+
+function greet() {
+  console.count();
+  return "hi " + user;
+}
+
+user = "bob";
+greet();
+user = "alice";
+greet();
+greet();
+console.count();
+ +

Sieht die Ausgabe in der Konsole in etwa so aus:

+ +
"default: 1"
+"default: 2"
+"default: 3"
+"default: 4"
+
+ +

Das Label wird als default angezeigt, da kein explizites Label angegeben wurde.

+ +

Wenn wir die Variable user als das Argument label an den ersten Aufruf von count() übergeben und den String "alice" an den zweiten:

+ +
let user = "";
+
+function greet() {
+  console.count(user);
+  return "hi " + user;
+}
+
+user = "bob";
+greet();
+user = "alice";
+greet();
+greet();
+console.count("alice");
+ +

Sieht die Ausgabe so aus:

+ +
"bob: 1"
+"alice: 1"
+"alice: 2"
+"alice: 3"
+ +

Wir führen jetzt separate Zählungen ein, die nur auf dem Wert von label basieren.

+ +
+
+ +

Spezifikation

+ + + + + + + + + + + + + + + + +
SpezifikationStatusKommentar
{{SpecName("Console API", "#count", "console.count()")}}{{Spec2("Console API")}}Initiale Definition
+ +

Browserkompatibilität

+ + + +

{{Compat("api.Console.count")}}

diff --git a/files/de/web/api/console/debug/index.html b/files/de/web/api/console/debug/index.html new file mode 100644 index 0000000000..15d8e258fc --- /dev/null +++ b/files/de/web/api/console/debug/index.html @@ -0,0 +1,63 @@ +--- +title: Console.debug() +slug: Web/API/Console/debug +translation_of: Web/API/Console/debug +--- +
{{APIRef("Console API")}}
+ +

Die Methode debug() gibt eine Nachricht der Protokollstufe "debug" auf der Konsole aus. Die Nachricht wird dem Benutzer nur angezeigt, wenn die Konsole für die Anzeige von Debug-Ausgaben konfiguriert ist.

+ +

{{AvailableInWorkers}}

+ +

Syntax

+ +
console.debug(obj1 [, obj2, ..., objN]);
+console.debug(msg [, subst1, ..., substN]);
+
+ +

Parameter

+ +
+
obj1 ... objN {{optional_inline}}
+
Eine Liste der auszugebenden JavaScript-Objekte. Die String-Darstellungen jedes dieser Objekte werden in der angegebenen Reihenfolge zusammengefügt und an die Konsole ausgegeben.
+
msg {{optional_inline}}
+
Ein JavaScript String, die keine oder mehrere Stringersetzungen enthält, die in aufeinanderfolgender Reihenfolge durch subst1 bis substN ersetzt werden.
+
subst1 ... substN {{optional_inline}}
+
JavaScript-Objekte, mit denen Stringersetzungen in msg ersetzt werden sollen. Dies gibt Ihnen zusätzliche Kontrolle über das Format der Ausgabe. Eine Beschreibung der Funktionsweise von Ersetzungen finden Sie unter {{SectionOnPage("/de-de/docs/Web/API/Console", "Verwenden von Ersatzstrings")}}.
+
+ +

Weitere Informationen finden Sie unter Text in der Konsole ausgeben in der Dokumentation des Objekts {{domxref("console")}}.

+ +

Spezifikationen

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("Console API", "#debug", "console.debug()")}}{{Spec2("Console API")}}Initiale definition
+ +

Browserkompatibilität

+ +
+ + +

{{Compat("api.Console.debug")}}

+
+ +

Siehe auch

+ + diff --git a/files/de/web/api/console/dir/index.html b/files/de/web/api/console/dir/index.html new file mode 100644 index 0000000000..bd54b88c46 --- /dev/null +++ b/files/de/web/api/console/dir/index.html @@ -0,0 +1,56 @@ +--- +title: Console.dir() +slug: Web/API/Console/dir +translation_of: Web/API/Console/dir +--- +
{{APIRef("Console API")}}
+ +

Zeigt eine interaktive Liste der Eigenschaften des angegebenen JavaScript-Objekts an. Die Ausgabe wird als hierarchische Liste mit Aufklapp-Dreiecken angezeigt, in denen Sie den Inhalt untergeordneter Objekte sehen können.

+ +

Mit anderen Worten: Mit console.dir() können Sie alle Eigenschaften eines angegebenen JavaScript-Objekts in der Konsole anzeigen und problemlos abrufen.

+ +

{{AvailableInWorkers}}

+ +

console-dir.png

+ +

Syntax

+ +
console.dir(object);
+
+ +

Parameter

+ +
+
object
+
Ein JavaScript-Objekt, dessen Eigenschaften angezeigt werden sollen.
+
+ +

Spezifikationen

+ + + + + + + + + + + + + + + + +
SpezifikationStatusKommentar
{{SpecName("Console API", "#consoledirobject", "console.dir()")}}{{Spec2("Console API")}}Initiale Definition
+ +

Browserkompatibilität

+ +

{{Compat("api.Console.dir")}}

+ +

Siehe auch

+ + diff --git a/files/de/web/api/console/index.html b/files/de/web/api/console/index.html new file mode 100644 index 0000000000..4f045815f1 --- /dev/null +++ b/files/de/web/api/console/index.html @@ -0,0 +1,296 @@ +--- +title: Console +slug: Web/API/Console +tags: + - API + - DOM + - Debugging + - Reference + - web console +translation_of: Web/API/Console +--- +
{{APIRef("Console API")}}
+ +

Das Console Objekt bietet Zurgiff auf die Debugging-Konsole des Browsers (z. B. die Web-Konsole in Firefox). Die Einzelheiten der Funktionsweise sind von Browser zu Browser unterschiedlich, es gibt jedoch de facto eine Reihe von Funktionen, die normalerweise bereitgestellt werden.

+ +

Auf das Console Objekt kann von jedem globalen Objekt aus zugegriffen werden. {{domxref("Window")}} im Browser und {{domxref("WorkerGlobalScope")}} als spezifische Varianten in Workern über die Property-Konsole. Es wird unter {{domxref("Window.console")}} zur Verfügung gestellt und kann als einfache Konsole referenziert werden. Zum Beispiel:

+ +
console.log("Failed to open the specified link")
+ +

Diese Seite dokumentiert die {{anch("Methods", "Methoden")}}, die für das Console Objekt verfügbar sind und enthält einige {{anch("Usage", "Anwendungsbeispiele")}}.

+ +

{{AvailableInWorkers}}

+ +

Methoden

+ +
+
{{domxref("Console.assert()")}}
+
Protokolliert eine Nachricht und eine Stack-Ablaufverfolgung in der Konsole, wenn das erste Argument false ist.
+
{{domxref("Console.clear()")}}
+
Leert die Konsole.
+
{{domxref("Console.count()")}}
+
Protokolliert, wie oft diese Zeile mit dem angegebenen Label aufgerufen wurde.
+
{{domxref("Console.countReset()")}}
+
Setzt den Wert des Zählers mit der angegebenen Bezeichnung zurück.
+
{{domxref("Console.debug()")}}
+
Gibt eine Nachricht mit der Protokollebene "debug" in der Konsole aus. +
Hinweis: Ab Chromium 58 wird diese Methode nur in Chromium-Browserkonsolen angezeigt, wenn die Stufe "Verbose" ausgewählt ist.
+
+
{{domxref("Console.dir()")}}
+
Zeigt eine interaktive Auflistung der Eigenschaften eines angegebenen JavaScript-Objekts an. In dieser Auflistung können Sie Offenlegungsdreiecke verwenden, um den Inhalt untergeordneter Objekte zu untersuchen.
+
{{domxref("Console.dirxml()")}}
+
+

Zeigt eine XML/HTML-Elementdarstellung des angegebenen Objekts an, falls möglich, oder die JavaScript-Objektansicht, falls dies nicht möglich ist.

+
+
{{domxref("Console.error()")}}
+
Gibt eine Fehlermeldung aus. Sie können Stringersetzung und zusätzliche Argumente mit dieser Methode verwenden.
+
{{domxref("Console.exception()")}} {{Non-standard_inline}} {{deprecated_inline}}
+
Ein Alias für error().
+
{{domxref("Console.group()")}}
+
Erstellt eine neue Inline-Gruppe, in der alle folgenden Ausgaben von einer anderen Ebene eingerückt werden. Um eine Ebene wieder zu verlassen, rufen Sie groupEnd() auf.
+
{{domxref("Console.groupCollapsed()")}}
+
Erstellt eine neue Inline-Gruppe, in der alle folgenden Ausgaben von einer anderen Ebene eingerückt werden. Anders als bei group() beginnt die Inline-Gruppe eingeklappt und muss über einen Button erst aufgeklappt werden. Um eine Ebene wieder zu verlassen, rufen Sie groupEnd() auf.
+
{{domxref("Console.groupEnd()")}}
+
Verlässt die aktuelle Inline-Gruppe.
+
{{domxref("Console.info()")}}
+
Informative Protokollierung von Informationen. Sie können Stringersetzung und zusätzliche Argumente mit dieser Methode verwenden.
+
{{domxref("Console.log()")}}
+
Zur allgemeinen Ausgabe von Protokollinformationen. Sie können Stringersetzung und zusätzliche Argumente mit dieser Methode verwenden.
+
{{domxref("Console.profile()")}} {{Non-standard_inline}}
+
Startet den integrierten Profiler des Browsers (z. B. das Firefox-Leistungstool). Sie können einen optionalen Namen für das Profil angeben.
+
{{domxref("Console.profileEnd()")}} {{Non-standard_inline}}
+
Stoppt den Profiler. Das resultierende Profil wird im Leistungstool des Browsers angezeigt (z. B. im Firefox-Leistungstool).
+
{{domxref("Console.table()")}}
+
Zeigt tabellarische Daten als Tabelle an.
+
{{domxref("Console.time()")}}
+
Startet einen Timer mit einem als Eingabeparameter angegebenen Namen. Auf einer Seite können bis zu 10.000 gleichzeitige Timer ausgeführt werden.
+
{{domxref("Console.timeEnd()")}}
+
Stoppt den angegebenen Timer und protokolliert die abgelaufene Zeit in Sekunden seit dem Start.
+
{{domxref("Console.timeLog()")}}
+
Protokolliert den Wert des angegebenen Timers in der Konsole.
+
{{domxref("Console.timeStamp()")}} {{Non-standard_inline}}
+
Fügt der Zeitleiste oder dem Wasserfallwerkzeug des Browsers eine Markierung hinzu.
+
{{domxref("Console.trace()")}}
+
Gibt eine Stapelablaufverfolgung (stack trace) aus.
+
{{domxref("Console.warn()")}}
+
Gibt eine Warnmeldung aus. Sie können Stringersetzung und zusätzliche Argumente mit dieser Methode verwenden.
+
+ +

Benutzung

+ +

Text auf der Konsole ausgeben

+ +

Die am häufigsten verwendete Funktion der Konsole ist das Protokollieren von Text und anderen Daten. Sie können vier Ausgabekategorien erstellen, die Sie mit den Methoden {{domxref("console.log()")}}, {{domxref("console.info()")}}, {{domxref("console.warn()")}} und {{domxref("console.error()")}} generieren können. Jedes dieser Ergebnisse hat eine unterschiedliche Ausgabe im Protokoll. Sie können die von Ihrem Browser bereitgestellten Filtersteuerelemente verwenden, um nur die Arten von Ausgaben anzuzeigen, die Sie interessieren.

+ +

Es gibt zwei Möglichkeiten, jede der Ausgabemethoden zu verwenden. Sie können einfach eine Liste von Objekten übergeben, deren Stringdarstellungen zu einem String verkettet werden, dann an die Konsole ausgegeben werden, oder Sie können einen String übergeben, der keine oder mehrere Ersatzstrings enthält, gefolgt von einer Liste von Objekten, um diese zu ersetzen.

+ +

Ein einzelnes Objekt ausgeben

+ +

Die einfachsten Methoden zur Verwendung der Protokollierungsmethoden sind die Ausgabe eines einzelnen Objekts:

+ +
var someObject = { str: "Some text", id: 5 };
+console.log(someObject);
+
+ +

Die Ausgabe sieht ungefähr so aus:

+ +
[09:27:13.475] ({str:"Some text", id:5})
+ +

Mehrere Objekte ausgeben

+ +

Sie können auch mehrere Objekte ausgeben, indem Sie sie beim Aufrufen der Protokollierungsmethode einfach nacheinander auflisten:

+ +
var car = "Dodge Charger";
+var someObject = { str: "Some text", id: 5 };
+console.info("My first car was a", car, ". The object is:", someObject);
+ +

Diese Ausgabe sieht folgendermaßen aus:

+ +
[09:28:22.711] My first car was a Dodge Charger . The object is: ({str:"Some text", id:5})
+
+ +

String-Ersetzungen verwenden

+ +

Wenn Sie einen String an eine der Methoden des Konsolenobjekts übergeben, die einen String akzeptiert (z. B. log()), können Sie folgende Ersatzstrings verwenden:

+ + + + + + + + + + + + + + + + + + + + + + + + +
ErsatzstringBeschreibung
%o ode %OGibt ein JavaScript-Objekt aus. Durch Klicken auf den Objektnamen werden weitere Informationen dazu im Inspektor geöffnet.
%d oder %i +

Gibt eine Ganzzahl aus. Zahlenformatierung wird unterstützt, z. B. gibt console.log("Foo %.2d", 1.1) die Zahl als zwei signifikante Ziffern mit einer führenden 0 aus: Foo 01

+
%sGibt einen String aus.
%f +

Gibt einen Gleitkommawert aus. Die Formatierung wird unterstützt, zum Beispiel gibt console.log("Foo %.2f", 1.1) die Zahl mit 2 Dezimalstellen aus: Foo 1.10

+
+ +
+

Hinweis: Die Präzisionsformatierung funktioniert in Chrome nicht

+
+ +

Jedes dieser Elemente zieht das nächste Argument nach dem Formatstring aus der Parameterliste. Zum Beispiel:

+ +
for (var i=0; i<5; i++) {
+  console.log("Hello, %s. You've called me %d times.", "Bob", i+1);
+}
+
+ +

Die Ausgabe sieht folgendermaßen aus:

+ +
[13:14:13.481] Hello, Bob. You've called me 1 times.
+[13:14:13.483] Hello, Bob. You've called me 2 times.
+[13:14:13.485] Hello, Bob. You've called me 3 times.
+[13:14:13.487] Hello, Bob. You've called me 4 times.
+[13:14:13.488] Hello, Bob. You've called me 5 times.
+
+ +

Konsolenausgaben stylen

+ +

Sie können die %c Direktive verwenden, um einen CSS-Stil auf die Konsolenausgabe anzuwenden:

+ +
console.log("This is %cMy stylish message", "color: yellow; font-style: italic; background-color: blue;padding: 2px");
+ +
Der Text vor der Direktive wird nicht beeinflusst. Der Text nach der Direktive wird jedoch mit den CSS-Deklarationen im Parameter formatiert.
+ +
 
+ +
+ +
 
+ +
+

Hinweis: Es werden etliche CSS-Eigenschaften von diesem Stil unterstützt. Sie sollten experimentieren und sehen, welche sich als nützlich erweisen.

+
+ +
 
+ +
{{h3_gecko_minversion("Gruppen in der Konsole verwenden", "9.0")}}
+ +

Sie können verschachtelte Gruppen verwenden, um Ihre Ausgabe zu organisieren, indem Sie verwandtes Material visuell kombinieren. Um einen neuen verschachtelten Block zu erstellen, rufen Sie console.group() auf. Die Methode console.groupCollapsed() ist ähnlich, erstellt den neuen Block jedoch zusammengeklappt und erfordert die Verwendung einer Schaltfläche zum Öffnen.

+ +
Hinweis: Minimierte Gruppen werden in Gecko noch nicht unterstützt. Die Methode groupCollapsed() ist zu diesem Zeitpunkt die gleiche wie group().
+ +

Um die aktuelle Gruppe zu verlassen, rufen Sie einfach console.groupEnd() auf. Zum Beispiel mit diesem 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");
+
+ +

Die Ausgabe sieht folgendermaßen aus:

+ +

nesting.png

+ +
{{h3_gecko_minversion("Timer", "10.0")}}
+ +

Um die Dauer einer bestimmten Operation zu berechnen, hat Gecko 10 die Unterstützung von Timern im console-Objekt eingeführt. Um einen Timer zu starten, rufen Sie die Methode console.time() auf und geben Sie ihm als einzigen Parameter einen Namen. Um den Timer zu stoppen und die verstrichene Zeit in Millisekunden abzurufen, rufen Sie einfach die Methode console.timeEnd() auf und übergeben den Namen des Timers erneut als Parameter. Auf einer Seite können bis zu 10.000 Timer gleichzeitig ausgeführt werden.

+ +

Zum Beispiel mit diesem Code:

+ +
console.time("answer time");
+alert("Click to continue");
+console.timeLog("answer time");
+alert("Do a bunch of other stuff...");
+console.timeEnd("answer time");
+
+ +

Protokolliert die Zeit, die der Benutzer zum Deaktivieren des Alert-Felds benötigt, schreibt die benötigte Zeit in der Konsole, wartet, bis der Benutzer die zweite Alert-Nachricht wegklickt und protokolliert dann die Endzeit in der Konsole:

+ +

timerresult.png

+ +

Beachten Sie, dass der Name des Timers sowohl beim Start als auch beim Stoppen des Timers angezeigt wird.

+ +
+

Hinweis: Es ist wichtig zu beachten, dass der Timer die Gesamtzeit für die Transaktion angibt, wenn Sie das Timing für den Netzwerkverkehr protokollieren. Die im Netzwerkbereich aufgeführte Zeit ist nur die Zeit, die der Header benötigt. Wenn Sie die Antwort-Body-Protokollierung aktiviert haben, sollte die angegebene Zeit für den Antwortheader und den Nachrichtentext der Anzeige in der Konsolenausgabe entsprechen.

+
+ +

Stapelverfolgung (Strack Traces)

+ +

Das Konsolenobjekt unterstützt auch die Ausgabe eines Stack-Trace. Daraufhin wird der Anrufpfad angezeigt, mit dem Sie den Punkt erreichen, an dem Sie {{domxref("console.trace()")}} aufrufen. Gegebener Code wie folgt:

+ +
function foo() {
+  function bar() {
+    console.trace();
+  }
+  bar();
+}
+
+foo();
+
+ +

Die Ausgabe in der Konsole sieht ungefähr so aus:

+ +

+ +

Spezifikationen

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Console API')}}{{Spec2('Console API')}}Initial definition.
+ +

Browserkompatibilität

+ + + +

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

+ +

Hinweise

+ + + +

Siehe auch

+ + + +

Andere Implementierungen

+ + diff --git a/files/de/web/api/console/log/index.html b/files/de/web/api/console/log/index.html new file mode 100644 index 0000000000..3f26aec9c3 --- /dev/null +++ b/files/de/web/api/console/log/index.html @@ -0,0 +1,180 @@ +--- +title: Console.log() +slug: Web/API/Console/log +tags: + - API + - Debugging + - NeedsBrowserCompatibility + - Web Entwicklung + - Web Konsole + - console + - console.dir + - console.log +translation_of: Web/API/Console/log +--- +
{{APIRef("Console API")}}
+ +

Gibt eine Nachricht auf der Web-Konsole aus.

+ +

{{AvailableInWorkers}}

+ +

Syntax

+ +
console.log(obj1 [, obj2, ..., objN]);
+console.log(msg [, subst1, ..., substN]);
+
+ +

Parameter

+ +
+
obj1 ... objN
+
Eine Liste von auszugebenden JavaScript-Objekten. Die Zeichenfolgedarstellungen der Objekte werden in der angegebenen Reihenfolge aneinandergehängt und ausgegeben.
+
msg
+
Eine JavaScript-Zeichenfolge, die Null oder mehr Ersatzzeichefolgen enthält.
+
subst1 ... substN
+
JavaScript-Objekte durch die die Ersatzzeichenfolgen in msg ersetzt werden sollen. Dies gibt Ihnen zusätzliche Kontrolle über die Formatierung der Ausgabe.
+
+ +

Weitere Details finden Sie im Abschnitt Outputting text to the console in der Dokumentation zu {{domxref("console")}}.

+ +

Spezifikationen

+ + + + + + + + + + + + + + + + +
SpezifikationStatusKommentar
{{SpecName("Console API", "#log", "console.log()")}}{{Spec2("Console API")}}Erste Definition
+ +

Browser Kompatibilität

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Grundlegende Unterstützung{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoDesktop("2.0")}}8{{CompatVersionUnknown}}{{CompatVersionUnknown}}
Ersatzzeichenfolgen{{CompatVersionUnknown}}
+ {{CompatChrome(28)}}[1]
{{CompatVersionUnknown}}{{CompatGeckoDesktop("9.0")}}10[2]{{CompatVersionUnknown}}{{CompatVersionUnknown}}
Verfügbar in Workers{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatGeckoDesktop("38.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Grundlegende Unterstützung{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("2.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Ersatzzeichenfolgen{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("9.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Verfügbar in Workers{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("38.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1] Weisst man %d einen negativen Wert zu, wird dieser zur nächsten negative Ganzzahl abgerundet; z. B. wird -0.1 zu -1.

+ +

[2] %c wird nicht unterstützt; %d wird als 0 angezeigt, falls der Wert keine Nummer ist.

+ +

Unterschied zu console.dir()

+ +

In Firefox generieren beide Kommandos dieselbe Ausgabe, wenn als Parameter ein DOM-Element mitgegeben wird: Man erhält in beiden Fällen eine JSON-artige Baumstruktur.

+ +

In Chrome besteht aber bei gleicher Eingabe ein nützlicher Unterschied:

+ +

+ +

Bemerkung:

+ + + +

Mit console.log werden DOM-Elemente also speziell behandelt. Bei console.dir ist dies nicht der Fall. Dies ist oft dann nützlich, wenn man die vollständige Darstellung des DOM-JS-Objekts ansehen möchte.

+ +

Mehr Informationen dazu finden Sie unter Chrome Console API reference.

+ +

Siehe auch

+ + diff --git a/files/de/web/api/console/table/index.html b/files/de/web/api/console/table/index.html new file mode 100644 index 0000000000..c641bf0c6f --- /dev/null +++ b/files/de/web/api/console/table/index.html @@ -0,0 +1,214 @@ +--- +title: Console.table() +slug: Web/API/Console/table +tags: + - Konsole + - Tabelle + - log + - tabellarisch +translation_of: Web/API/Console/table +--- +
{{APIRef("Console API")}}
+ +

Zeigt tabellarische Daten als Tabelle im Log an.

+ +

Diese Funktion benötigt einen Parameter data, welcher ein Array oder ein Objekt sein muss und außerdem einen optionalen Parameter columns.

+ +

Die Funktion zeigt data als Tabelle im Log an. Jedes Element im Array (bzw. jede zählbare Eigenschaft im data Objekt) wird als Tabellenzeile angezeigt.

+ +

Die erste Tabellenspalte wird mit (index) bezeichnet. Wenn data ein Array ist, dann erscheinen in dieser Spalte die Arrayindizes. Wenn data ein Objekt ist, dann erscheinen in dieser Spalte die Eigenschaftsnamen. Beachten Sie, dass (bei Firefox) console.table maximal 1000 Zeilen anzeigt. (Die erste Zeile ist die Überschriftszeile mit der Bezeichnung index).

+ +

{{AvailableInWorkers}}

+ +

Sammlungen (Collections) mit primitiven Datentypen

+ +

Der data Parameter kann ein Array oder ein Objekt sein.

+ +
// Ein String-Array
+
+console.table(["apples", "oranges", "bananas"]);
+ +

+ +
// Ein Objekt mit Eigenschaften, die Strings sind
+
+function Person(firstName, lastName) {
+  this.firstName = firstName;
+  this.lastName = lastName;
+}
+
+var me = new Person("John", "Smith");
+
+console.table(me);
+ +

+ +

Sammlungen (Collections) mit zusammengesetzen Typen

+ +

Wenn die Arrayinhalte oder die Objekteigenschaften selbt Arrays oder Objekte sind, dann werden deren Elemente einzeln in jeder Spalte dargestellt:

+ +
// Ein Array, welches Arrays enthält
+
+var people = [["John", "Smith"], ["Jane", "Doe"], ["Emily", "Jones"]]
+console.table(people);
+ +

Table displaying array of arrays

+ +
// Ein Array mit Objekten
+
+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]);
+ +

Beachten Sie: Wenn das Array Objekte enthält, dann werden die Spalten mit dem Eigenschaftsnamen beschriftet.

+ +

Table displaying array of objects

+ +
// Ein Objekt mit Eigenschaften, welche wiederum ein
+// Objekt sind
+
+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

+ +

Auswahl der anzuzeigenden Spalten

+ +

Nromalerweise zeigt console.table() alle Elemente in jeder Zeile an. Sie können aber den optionalen Parameter columns verwenden, um nur bestimmte Spalten anzuzeigen:

+ +
// Ein Array mit Objekten, nur der "firstName"
+// wird angezeigt.
+
+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

+ +

Tabelle sortieren

+ +

Sie können die Tabelle durch einen Klick auf den jeweiligen Spaltenkopf umsortieren.

+ +

Syntax

+ +
console.table(data [, columns]);
+
+ +

Parameter

+ +
+
data
+
Die anzuzeigenden Daten. Diese müssen ein Array oder ein Objekt sein.
+
columns
+
Ein Array mit den anzuzeigenden Spalten.
+
+ +

Spezifikationen

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("Console API", "#table", "console.table()")}}{{Spec2("Console API")}}Initial definition
+ +

Browserkompatibilität

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoDesktop("34.0")}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
Available in workers{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoDesktop("38.0")}}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("34.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Available in workers{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("38.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
diff --git a/files/de/web/api/console/time/index.html b/files/de/web/api/console/time/index.html new file mode 100644 index 0000000000..850c459e99 --- /dev/null +++ b/files/de/web/api/console/time/index.html @@ -0,0 +1,56 @@ +--- +title: Console.time() +slug: Web/API/Console/time +translation_of: Web/API/Console/time +--- +
{{APIRef("Console API")}}
+ +

Startet einen Timer, den man benutzen kann, um zu überprüfen wie lange eine bestimmte Operation. Man kann jedem Timer einen einzigartigen Namen geben und kann bis zu 10000 Timer gleichzeitig auf einer Seite laufen lassen. Wenn man {{domxref("console.timeEnd()")}} mit dem selben Namen aufruft, gibt der Browser die Zeit in Millisekunden zurück, die seit dem Starten des Timers verstrichen ist.

+ +

Siehe auch Timer in der {{domxref("console")}} Dokumentation für weitere Details und Beispiele.

+ +

{{AvailableInWorkers}}

+ +

Syntax

+ +
console.time(Bezeichnung);
+
+ +

Parameter

+ +
+
Bezeichnung
+
Der Name des neuen Timers. Dieser wird den Timer identifizieren; Der selbe Name sollte beim aufrufen von {{domxref("console.timeEnd()")}} genutzt werden, um den Timer zu stoppen und das Ergebnis in die Konsole zu drucken.
+
+ +

Spezifikationen

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("Console API", "#time", "console.time()")}}{{Spec2("Console API")}}Initial definition
+ +

Browser compatibility

+ + + +

{{Compat("api.Console.time")}}

+ +

See also

+ + diff --git a/files/de/web/api/console/timeend/index.html b/files/de/web/api/console/timeend/index.html new file mode 100644 index 0000000000..65c6242a83 --- /dev/null +++ b/files/de/web/api/console/timeend/index.html @@ -0,0 +1,57 @@ +--- +title: Console.timeEnd() +slug: Web/API/Console/timeEnd +translation_of: Web/API/Console/timeEnd +--- +
{{APIRef("Console API")}}
+ +

Stopt einen Timer, der zuvor mit {{domxref("console.time()")}} gestartet wurde.

+ +

Siehe auch Timer in der Dokumentation für mehr Details und Beispiele

+ +

{{AvailableInWorkers}}

+ +

Syntax

+ +
console.timeEnd(Bezeichnung);
+
+ +

Parameter

+ +
+
Bezeichnung
+
Der Name des zu stoppenden Timers. Nachdem der Timer gestoppt wurde, wird die verstrichene Zeit automatisch in der Web Konsole ausgegeben.
+
+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("Console API", "#timeend", "console.timeEnd()")}}{{Spec2("Console API")}}Initial definition
+ +

Browser compatibility

+ +
+ + +

{{Compat("api.Console.timeEnd")}}

+
+ +

See also

+ + diff --git a/files/de/web/api/console/warn/index.html b/files/de/web/api/console/warn/index.html new file mode 100644 index 0000000000..a481fda12b --- /dev/null +++ b/files/de/web/api/console/warn/index.html @@ -0,0 +1,147 @@ +--- +title: Console.warn() +slug: Web/API/Console/warn +translation_of: Web/API/Console/warn +--- +
{{APIRef("Console API")}}{{non-standard_header}}
+ +

Ausgabe einer Warnmeldung in der Web-Konsole.

+ +

{{AvailableInWorkers}}

+ +

{{Note("In Firefox haben Warnungen in der Web-Console ein kleines Ausrufzeichen Symbol neben dem Meldungstext.")}}

+ +

Syntax

+ +
console.warn(obj1 [, obj2, ..., objN]);
+console.warn(msg [, subst1, ..., substN]);
+
+ +

Parameter

+ +
+
obj1 ... objN
+
Eine Liste von JavaScript Objecten, die ausgegeben werden sollen. Die String-Darstellung jedes einzelnen Objekts wird in der angegebenen Reihenfolge aneinander gehangen und ausgegeben.
+
msg
+
Ein JavaScript String der keinen oder mehrere Platzhalter-Strings enthält.
+
subst1 ... substN
+
JavaScript Objekte, die in die Platzhalter-Strings in msg eingesetzt werden. Dadurch kann das Ausgabeformat der Meldung zusätzlich beeinflusst werden.
+
+ +

Sie Textausgabe in der Konsole in der Dokumentation von {{domxref("console")}} für weitere Details.

+ +

Spekifikationen

+ + + + + + + + + + + + + + + + +
SpezifikationStatusKommentar
{{SpecName("Console API", "#consolewarnobject--object-", "console.warn()")}}{{Spec2("Console API")}}Initial definition
+ +

Browser Kompatibilität

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoDesktop("2.0")}}8{{CompatVersionUnknown}}{{CompatVersionUnknown}}
Substitution strings{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoDesktop("9.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Available in workers{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoDesktop("38.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("2.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Substitution strings{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile("9.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Available in workers{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile("38.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

Siehe auch

+ + diff --git a/files/de/web/api/crypto/index.html b/files/de/web/api/crypto/index.html new file mode 100644 index 0000000000..0bf9eb23fc --- /dev/null +++ b/files/de/web/api/crypto/index.html @@ -0,0 +1,68 @@ +--- +title: Crypto +slug: Web/API/Crypto +tags: + - API + - Interface + - Referenz + - Schnittstelle + - Web Crypto API +translation_of: Web/API/Crypto +--- +

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

+ +

Die Crypto-Schnittstelle bietet grundlegende kryptographische Funktionen, die im aktuellen Kontext verfügbar sind. Sie ermöglicht den Zugriff auf kryptographische Primitive wie z.B. einen verschlüsselungstechnisch starken Zufallszahlengenerator.

+ +

Ein Objekt mit dieser Schnittstelle ist im Web-Kontext über die Eigenschaft {{domxref("Window.crypto")}} verfügbar.

+ +

Eigenschaften

+ +

Diese Schnittstelle implementiert Eigenschaften, die unter {{domxref("RandomSource")}} definiert sind.

+ +
+
{{domxref("Crypto.subtle")}} {{readOnlyInline}}
+
Gibt ein {{domxref("SubtleCrypto")}}-Objekt zurück, das Zugriff auf einfache kryptographische Methoden wie Hash-Funktionen, Signierung, Ver- und Entschlüsselung ermöglicht.
+
 
+
+ +

Methoden

+ +

Diese Schnittstelle implementiert Methoden, die unter {{domxref("RandomSource")}} beschrieben sind.

+ +
+
{{domxref("Crypto.getRandomValues()")}}
+
Füllt das übergebene {{ jsxref("TypedArray") }} mit kryptographisch sinnvollen Zufallswerten.
+
+ +

Spezifikationen

+ + + + + + + + + + + + + + + + +
SpezifikationStatusKommentar
{{SpecName("Web Crypto API", "#crypto-interface", "Crypto")}}{{Spec2("Web Crypto API")}}Ursprüngliche Definition
+ +

Browser-Kompatibilität

+ +
+ + +

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

+
+ +

Siehe auch

+ + diff --git a/files/de/web/api/css/escape/index.html b/files/de/web/api/css/escape/index.html new file mode 100644 index 0000000000..904da32560 --- /dev/null +++ b/files/de/web/api/css/escape/index.html @@ -0,0 +1,79 @@ +--- +title: CSS.escape() +slug: Web/API/CSS/escape +tags: + - API + - CSS + - CSSOM + - Méthode + - Referenz + - Statisch + - escape() + - maskieren +translation_of: Web/API/CSS/escape +--- +

{{APIRef("CSSOM")}}{{SeeCompatTable}}

+ +

Die statische Methode CSS.escape() gibt ein {{DOMxRef("CSSOMString")}} zurück, das die maskierte Zeichenfolge des übergebenen String Parameters enthält, hauptsächlich zur Verwendung als Teil eines CSS Selektors.

+ +

Syntax

+ +
escapedStr = CSS.escape(str);
+
+ +

Parameter

+ +
+
str
+
Die zu maskierende Zeichenfolge {{DOMxRef("CSSOMString")}}.
+
+ +

Beispiele

+ +

Grundlegende Ergebnisse

+ +
CSS.escape(".foo#bar")        // "\.foo\#bar"
+CSS.escape("()[]{}")          // "\(\)\[\]\\{\\}"
+CSS.escape('--a')             // "--a"
+CSS.escape(0)                 // "\30 ", the Unicode code point of '0' is 30
+CSS.escape('\0')              // "\ufffd", the Unicode REPLACEMENT CHARACTER
+ +

Verwendung im Kontext

+ +

Um einen String als Teil eines Selektors zu maskieren kann die escape() Methode verwendet werden:

+ +
var element = document.querySelector('#' + CSS.escape(id) + ' > img');
+ +

Die escape() Methode kann auch verwendet werden um Strings zu maskieren. Die Maskierung wird dabei auf Zeichen angewendet, die streng genommen nicht maskiert werden müssen.

+ +
var element = document.querySelector('a[href="#' + CSS.escape(fragment) + '"]');
+ +

Spezifikation

+ + + + + + + + + + + + + + +
SpezifikationStatusKommentar
{{SpecName('CSSOM', '#the-css.escape()-method', 'CSS.escape()')}}{{Spec2('CSSOM')}}Initial definition
+ +

Browserkompatibilität

+ + + +

{{Compat("api.CSS.escape")}}

+ +

Siehe auch

+ + diff --git a/files/de/web/api/css/index.html b/files/de/web/api/css/index.html new file mode 100644 index 0000000000..fe659bba03 --- /dev/null +++ b/files/de/web/api/css/index.html @@ -0,0 +1,90 @@ +--- +title: CSS +slug: Web/API/CSS +tags: + - API + - CSSOM + - Interface + - NeedsTranslation + - Painting + - Reference + - TopicStub +translation_of: Web/API/CSS +--- +
{{APIRef("CSSOM")}}
+ +

The CSS interface holds useful CSS-related methods. No objects with this interface are implemented: it contains only static methods and is therefore a utilitarian interface.

+ +

Properties

+ +

The CSS interface is a utility interface and no object of this type can be created: only static properties are defined on it.

+ +

Static properties

+ +
+
{{DOMxRef("CSS.paintWorklet")}} {{Experimental_Inline}}{{SecureContext_Inline}}
+
Provides access to the Worklet responsible for all the classes related to painting.
+
+ +

Methods

+ +

The CSS interface is a utility interface and no object of this type can be created: only static methods are defined on it.

+ +

Static methods

+ +

No inherited static methods.

+ +
+
{{DOMxRef("CSS.registerProperty()")}}
+
Registers {{cssxref('--*', 'custom properties')}}, allowing for property type checking, default values, and properties that do or do not inherit their value.
+
{{DOMxRef("CSS.supports()")}}
+
Returns a {{JSxRef("Boolean")}} indicating if the pair property-value, or the condition, given in parameter is supported.
+
{{DOMxRef("CSS.escape()")}}
+
Can be used to escape a string mostly for use as part of a CSS selector.
+
{{DOMxRef("CSS.factory_functions", 'CSS factory functions')}}
+
Can be used to return a new CSSUnitValue with a value of the parameter number of the units of the name of the factory function method used.
+
+
CSS.em(3) // CSSUnitValue {value: 3, unit: "em"}
+
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS Painting API','#dom-css-paintworklet','paintWorklet')}}{{Spec2('CSS Painting API')}}Adds the paintWorklet static property.
{{SpecName('CSSOM', '#the-css.escape()-method', 'CSS')}}{{Spec2('CSSOM')}}Adds the escape() static method.
{{SpecName('CSS3 Conditional', '#the-css-interface', 'CSS')}}{{Spec2('CSS3 Conditional')}}Initial definition
+ +

Browser compatibility

+ + + +

{{Compat("api.CSS", 1)}}

+ +

See Also

+ + diff --git a/files/de/web/api/css_painting_api/guide/index.html b/files/de/web/api/css_painting_api/guide/index.html new file mode 100644 index 0000000000..536040de4e --- /dev/null +++ b/files/de/web/api/css_painting_api/guide/index.html @@ -0,0 +1,534 @@ +--- +title: Die CSS Painting API verwenden +slug: Web/API/CSS_Painting_API/Guide +translation_of: Web/API/CSS_Painting_API/Guide +--- +

Die CSS Paint API wurde entworfen, um Entwicklern zu ermöglichen, programmatisch Bilder festzulegen, die überall dort verwendet werden können, wo ein CSS Bild aufgerufen werden kann, wie in CSS background-image, border-image, mask-image, etc.

+ +

Um programmatisch ein Bild zu erstellen, das von einem CSS stylesheet verwendet wird, müssen wir folgende Schritte abarbeiten:

+ +
    +
  1. Lege ein "paint worklet" mit der registerPaint() Funktion fest.
  2. +
  3. Melde das worklet an.
  4. +
  5. Binde mit Include die {{cssxref('paint()','paint()')}} CSS Funktion ein.
  6. +
+ +

Zum besseren Verständnis dieser einzelnen Schritte werden wir eine halbhohe farbliche Markierung wie in folgender Titelzeile erstellen:

+ +

Text reading 'My Cool Header' with a solid yellow background image block on the bottom left two thirds of the header

+ +

CSS paint worklet

+ +

In einer externen Skript-Datei nutzen wir die registerPaint() Funktion, um unser CSS Paint worklet zu benennen. Diese benötigt zwei Parameter. Der erste ist der Name, den wir dem worklet geben — diesen Namen werden wir als einen Parameter von der paint() Funktion verwenden, wenn wir das Bild einem Element hinzufügen wollen. Der zweite Parameter ist die Klasse, die die ganze Magie ausführt: die die Kontext-Entscheidungen festlegt und natürlich das Bild, das wir auf unsere Oberfläche malen wollen.

+ +
registerPaint('headerHighlight', class {
+
+  /*
+       definiere dies, wenn die Alphatransparenz erlaubt ist;
+       alpha ist standardmäßig true; wenn auf false gesetzt, sind
+       alle Farben, die auf der Canvas genutzt werden, opak
+    */
+  static get contextOptions() {
+           return { alpha: true };
+    }
+
+    /*
+        ctx ist der 2D Zeichen Kontext
+        eine Untermenge der HTML5 Canvas API.
+    */
+  paint(ctx) {
+        ctx.fillStyle = 'hsla(55, 90%, 60%, 1.0)';
+        ctx.fillRect(0, 15, 200, 20);     /* order: x, y, w, h */
+  }
+});
+ +

In diesem Klassenbeispiel haben wir die Umstände (options) eines einzelnen Kontexts mit der contextOptions() Funktion festgelegt: wir haben ein einfaches Objekt zurückgegeben, das aussagt, dass die Alphatransparenz erlaubt ist.

+ +

Wir haben dann die paint() Funktion verwendet, um unser Objekt auf die Canvas zu zeichnen.

+ +

Die paint() Funktion kann drei Parameter aufnehmen. Hier übergeben wir nur ein Argument: den Rendering Kontext (wir schauen uns das im weiteren Verlauf noch genauer an), der oftmals mit dem Variablennamen ctx bezeichnet wird. Der 2D Rendering Context ist eine Untermenge der HTML5 Canvas API; die Version, die für CSS Houdini verfügbar is (auch PaintRenderingContext2D genannt), ist eine weitere Untermenge, die über die meisten Zusätze verfügt, die auch in der Canvas API vorhanden sind, mit Ausnahme von CanvasImageData, CanvasUserInterface, CanvasText, und CanvasTextDrawingStyles APIs.

+ +

Wir weisen mit fillStyle den Wert hsla(55, 90%, 60%, 1.0) zu, ein blasses Gelb, und rufen dann fillRect() auf, um ein farbiges Rechteck zu erstellen. Die Parameter von fillRect() sind, in der Abfolge, x-Achse und y-Achse (und zugleich die feste Koordinate), Breite und Höhe. fillRect(0, 15, 200, 20) erstellt ein Rechteck von 200 Einheiten Breite und 20 Einheiten Höhe, die 0 Einheiten von der linken und 15 Einheiten von der oberen Seite der Box entfernt sind, in der das Rechteck eingezeichnet wird.

+ +

Wir können die CSS background-size and background-position Eigenschaften (properties) verwenden, um das Hintergrundbild in seiner Größe und Position zu verändern, aber die oben festgelegten Werte sind die Standardwerte der gelben Box, die wir in unserem paint worklet definiert haben.

+ +

Wir haben dieses Beispiel einfach gehalten. Für mehr Möglichkeiten werfen Sie bitte einen Blick in die Canvas Dokumentation. Wir werden weiter unten im Tutorial auch komplexere Beispiele nutzen.

+ +

Das paint worklet verwenden

+ +

Um das paint worklet zu verwenden, müssen wir dies mit addModule() anmelden und in unsere CSS einfügen, wobei wir sicherstellen müssen, dass der CSS Selektor zu einem DOM Knoten in unserem HTML-Code passt.

+ +

Das worklet anmelden

+ +

Wir haben unser paint worklet in einer externen script-Datei erstellt, wie oben geziegt. Wir müssen jetzt unser worklet in unserer Hauptanwendung anmelden:

+ +
CSS.paintWorklet.addModule('nameOfPaintWorkletFile.js');
+ +

Dazu benutzen wir die von Paint Worklet bereitgestellte Funktion addModule() in einem <script>-Block innerhalb unseres HTML oder in einer externen JavaScript-Datei, die dann seinerseits von der Hauptanwendung aufgerufen werden muss.

+ +

In unserem Beispiel ist das worklet auf GitHub gespeichert.

+ +
+
CSS.paintWorklet.addModule('https://mdn.github.io/houdini-examples/cssPaint/intro/01partOne/header-highlight.js');
+ +

Auf das paint worklet in CSS verweisen

+ +

Haben wir das paint worklet angemeldet, können wir es in CSS benutzen. Dabei kann man die Funktion paint() so benutzen, wie man auch jeden anderen <image> Typ verwendet. In paint() wird als Parameter derselbe Name des worklets übergeben, den wir bei registerPaint() eingetragen haben.

+ +
.fancy {
+  background-image: paint(headerHighlight);
+}
+ +

Alles zusammensetzen

+ +

Nun können wir die fancy-Klasse aus CSS einem HTML-Element ganz normal in der Property class übergeben, um die gelbe Box als Hintergrundbild erscheinen zu lassen:

+ +
<h1 class="fancy">My Cool Header</h1>
+ +

Das folgende Beispiel wird wie das obige Beispiel in einem Browsers, der die CSS Painting API unterstützt, aussehen.

+
+ +

{{EmbedLiveSample("paintapi", 120, 120)}}

+ +

Während Sie vom HTML aus das worklet nicht mehr (innerlich) verändern können, können Sie trotzdem mit CSS über background-size und background-position Größe und Position des Bildes anpassen.

+ +

PaintSize

+ +

Im Beispiel oben haben wir eine Box aus 20x200 Einheiten erstellt, die 15 Einheiten vom oberen Rand der umgebenen Box - eines HTML-Elements - entfernt liegt, gleichgültig, welche Größe die umhüllende Box selbst hat. Ist der Text klein, sieht die Box wie eine große Unterstreichung aus, ist er groß und lang, ist die Box gleich einem Balken unter den ersten Buchstaben. Günstiger wäre aber, wenn das Hintergrundbild relativ zur Größe des umhüllenden Elementes wäre. Dafür können wir die paintSize Property, bzw. size.width und size.height, verwenden. Diese übernimmt die Breite und Höhe des umliegenden Elements und rechnet die Größe des worklets dafür aus.

+ +

The background is 50% of the height and 60% of the width of the element

+ +

In diesem Beispiel-Bild ist der Hintergrund proportional zu der Größe des umhüllenden Elements. Das dritte Beispiel hat als Breite width: 50%; das Hintergrundbild passt sich in den ersten beiden Beispielen der Größe der Schrift an und damit der Höhe des Blocks, im dritten Beispiel sieht man aber auch deutlich, dass die Breite ebenfalls passend gemacht wird.

+ +

Der Code, mit dem das möglich ist, sieht dann folgendermaßen aus:

+ +
registerPaint('headerHighlight', class {
+
+  static get contextOptions() {
+           return { alpha: true };
+  }
+
+    /*
+        ctx is the 2D drawing context
+        size is the paintSize, the dimensions (height and width) of the box being painted
+    */
+
+  paint(ctx, size) {
+        ctx.fillStyle = 'hsla(55, 90%, 60%, 1.0)';
+        ctx.fillRect( 0, size.height / 3, size.width * 0.4, size.height * 0.6 );
+  }
+});
+ +

Der Code unterscheidet sich an zwei Stellen vom ersten Beispiel:

+ +
    +
  1. Wir haben ein zweites Argument in paint() eingefügt, die Größe size.
  2. +
  3. Wir berechnen die Dimensionen und die Position unseres Rechtecks relativ zu dieser Größe size und nicht mehr mit absoluten Werten, mit Hilfe der Properties .width und .height.
  4. +
+ +

Unsere HTML-Elemente haben nur ein Hintergrundbild, welches sich in Größe und Breite ändert.

+ + + +

Wenn du mit diesem worklet herumspielst, kannst du dessen Größe über die Eigenschaften font-size und width des umhüllenden Elements ändern.

+ +

In Browsern, die CSS Paint API unterstützen, erscheint das unten aufgeführte Beispielt wie das Bild oben.

+ +

{{EmbedLiveSample("example2", 300, 300)}}

+ +

Properties anpassen

+ +

Zusätzlich zu der Größe des Elements kann ein worklet auch auf andere CSS-Eigenschaften zugreifen.

+ +
registerPaint('cssPaintFunctionName', class {
+     static get inputProperties() { return ['PropertyName1', '--customPropertyName2']; }
+     static get inputArguments() { return ['<color>']; }
+     static get contextOptions() { return {alpha: true}; }
+
+     paint(drawingContext, elementSize, styleMap) {
+         // Paint code goes here.
+     }
+});
+
+ +

Die drei Parameter der Funktion paint() enthalten den Zeichenkontext, die Größe des Malgrundes (meist des umgebenden Elements) und Eigenschaften (properties). Um auf die Eigenschaften zugreifen zu können, muss man die statische Methode inputProperties() aufrufen, die den Zugriff auf die CSS properties ermöglicht, sowohl der regulären als auch angepasster Eigenschaften. Diese liefert ein array mit den Namen der Eigenschaften zurück (wir werfen im letzten Abschnitt einen näheren Blick auf inputArguments).

+ +

Example

+ +
+

Legen wir dazu eine Liste an, deren Hintergrundbild zwischen drei verschiedenen Farben und drei unterschiedlichen Breiten wechselt.

+ +

The width and color of the background image changes based on the custom properties

+ +

In unserer CSS weisen wir verschiedene Farben und eine Anpassung der Breite des worklets über die --boxColor und --widthSubtractor Eigenschaften zu.

+ + + + + +
li {
+   background-image: paint(boxbg);
+   --boxColor: hsla(55, 90%, 60%, 1.0);
+}
+
+li:nth-of-type(3n) {
+   --boxColor: hsla(155, 90%, 60%, 1.0);
+   --widthSubtractor: 20;
+}
+
+li:nth-of-type(3n+1) {
+   --boxColor: hsla(255, 90%, 60%, 1.0);
+   --widthSubtractor: 40;
+}
+
+ +

Beachte, dass wir im CSS Eigenschaften verwenden, die nicht zum normalen CSS gehören, sondern von uns selbst definiert worden sind: boxColor und widthSubtractor. Auf diese können wir im worklet zugreifen, wenn wir diese über inputProperties() zugänglich machen.

+ +
registerPaint('boxbg', class {
+
+  static get contextOptions() { return {alpha: true}; }
+
+  /*
+     use this function to retrieve any custom properties (or regular properties, such as 'height')
+     defined for the element, return them in the specified array
+  */
+  static get inputProperties() { return ['--boxColor', '--widthSubtractor']; }
+
+  paint(ctx, size, props) {
+    /*
+       ctx -> drawing context
+       size -> paintSize: width and height
+       props -> properties: get() method
+    */
+
+    ctx.fillStyle = props.get('--boxColor');
+    ctx.fillRect(0, size.height/3, size.width*0.4 - props.get('--widthSubtractor'), size.height*0.6);
+  }
+});
+ +

Wir haben die Methode inputProperties() in der registerPaint() Klasse verwendet, um die Werte der beiden von uns definierten Eigenschaften zu erhalten, die das worklet boxbg anwenden. Mit inputProperties() legen wir uns einen Array an, der normale CSS-Eigenschaften wie auch selbst definierte erhalten kann.

+ +

In unserem <script>-Block melden wir das worklet an:

+ +
+
CSS.paintWorklet.addModule('https://mdn.github.io/houdini-examples/cssPaint/intro/worklet/boxbg.js');
+
+ +

{{EmbedLiveSample("example3", 300, 300)}}

+ +

In der Anwendung können wir zwar nicht das Script des worklets verändern, aber alle Werte, die über CSS übergeben werden und die vom worklet verarbeitet werden.

+ +

Komplexität hinzufügen

+ +

Das obenstehende Beispiel ist nicht sonderlich aufregend, da man es ebenso mit CSS in wenigen Schritten und ohne den Aufwand eines worklets programmieren kann, etwa, indem man dekorative Inhalte mit ::before hinzufügt oder mit background: linear-gradient(yellow, yellow) 0 15px / 200px 20px no-repeat; - Was die CSS Painting API so interessant und machtvoll macht, ist die Möglichkeit, komplexe Bilder zu erstellen und Variablen zu übergeben.

+ +

Werfen wir einen Blick auf ein komplexeres Beispiel.

+ +
registerPaint('headerHighlight', class {
+  static get inputProperties() { return ['--highColour']; }
+  static get contextOptions() { return {alpha: true}; }
+
+  paint(ctx, size, props) {
+
+		/* set where to start the highlight & dimensions */
+		const x = 0;
+		const y = size.height * 0.3;
+		const blockWidth = size.width * 0.33;
+		const highlightHeight = size.height * 0.85;
+        const color = props.get('--highColour');
+
+		ctx.fillStyle = color;
+
+		ctx.beginPath();
+		ctx.moveTo( x, y );
+		ctx.lineTo( blockWidth, y );
+		ctx.lineTo( blockWidth + highlightHeight, highlightHeight );
+		ctx.lineTo( x, highlightHeight );
+		ctx.lineTo( x, y );
+		ctx.closePath();
+		ctx.fill();
+
+		/* create the dashes */
+		for (let i = 0; i < 4; i++) {
+			let start = i * 2;
+			ctx.beginPath();
+			ctx.moveTo( (blockWidth) + (start * 10) + 10, y );
+			ctx.lineTo( (blockWidth) + (start * 10) + 20, y );
+			ctx.lineTo( (blockWidth) + (start * 10) + 20 + (highlightHeight), highlightHeight );
+			ctx.lineTo( (blockWidth) + (start * 10) + 10 + (highlightHeight), highlightHeight );
+			ctx.lineTo( (blockWidth) + (start * 10) + 10, y );
+			ctx.closePath();
+			ctx.fill();
+		}
+  } // paint
+});
+ +
+

Wir können dann einige Zeilen HTML mit der entsprechenden Klasse aus CSS schreiben:

+ +
<h1 class="fancy">Largest Header</h1>
+<h3 class="fancy">Medium size header</h3>
+<h6 class="fancy">Smallest Header</h6>
+ +

Dann geben wir den einzelnen HTML-Elementen je einen verschiedenen Wert für die von uns definierte Eigenschaft --highColour:

+ +
.fancy {
+  background-image: paint(headerHighlight);
+}
+h1 { --highColour: hsla(155, 90%, 60%, 0.7); }
+h3 { --highColour: hsla(255, 90%, 60%, 0.5); }
+h6 { --highColour: hsla(355, 90%, 60%, 0.3); }
+ +

Und wir melden das worklet an:

+ +
CSS.paintWorklet.addModule('https://mdn.github.io/houdini-examples/cssPaint/intro/03partThree/header-highlight.js');
+ +

{{EmbedLiveSample("example4", 300, 300)}}

+ +

Während man das worklet selbst nicht ändern kann, kann man mit CSS und HTML jedoch herumspielen. Vielleicht probieren Sie mal float und clear bei den Titelzeilen <h1>, <h3> und <h6> aus.

+ +

Man kann natürlich auch Hintergrundbilder ohne CSS paint API erstellen. Das kann allerdings zu einem großen Mehraufwand und wesentlich mehr Code führen. Mit CSS Paint API kann ein worklet immer wieder verwendet werden und über eine Parameter-Übergabe rasch angepasst werden.

+
+ +

Parameter übergeben

+ +

Mit der CSS Paint API können wir nicht nur auf selbstdefinierte Eigenschaften zugreifen, sondern auch über die CSS-Funktion paint() auch Parameter übergeben.

+ +

Nehmen wir an, wir wollen ab und zu den Hintergrund nur mit einem Strich statt vollständig füllen. Dafür können wir ein Extra-Argument übergeben, welches dann im worklet abgefragt und entsprechend verarbeitet wird.

+ +
li {
+	background-image: paint(hollowHighlights, stroke);
+}
+
+ +

Mit der Methode inputArguments() in der Klasse registerPaint() machen wir das zusätzliche Argument aus der CSS-Funktion paint() zugänglich:

+ +
static get inputArguments() { return ['*']; }
+
+ +

Und wenn wir darauf zugreifen wollen:

+ +
paint(ctx, size, props, args) {
+
+	// use our custom arguments
+	const hasStroke = args[0].toString();
+
+	// if stroke arg is 'stroke', don't fill
+	if (hasStroke === 'stroke') {
+		ctx.fillStyle = 'transparent';
+		ctx.strokeStyle = colour;
+	}
+	...
+}
+
+ +

Wir können auch mehr als ein Argument übergeben:

+ +
li {
+	background-image: paint(hollowHighlights, stroke, 10px);
+}
+
+ +

Wir können auch den Datentyp genau angeben. Wenn wir die Werte der Argumente mit get holen, fragen wir dann speziell nach einer <length> Einheit.

+ +
static get inputArguments() { return ['*', '<length>']; }
+ +

In diesem Fall haben wir spezifisch nach einem <length> Attribut gefragt. Das erste Element des Arrays wird dann als CSSUnparsedValue, das zweite als CSSStyleValue übergeben.

+ +

Wenn das selbstdefinierte Argument ein CSS-Wert ist, zum Beispiel eine Maßeinheit, können wir die Typed OM CSSStyleValue Klasse (und deren Unterklassen) aufrufen, indem wir das Schlüsselwort für diesen Typen in der Methode inputArguments() nutzen.

+ +

Fügen wir einfach ein weiteres Argument für die Pixel-Breite unserer Hintergrundlinie hinzu:

+ +
li {
+	background-image: paint(hollowHighlights, stroke, 10px);
+}
+
+ +

Wenn wir mit get unsere Argumentenliste holen, können wir direkt nach der <length> Einheit fragen.

+ +
static get inputArguments() { return ['*', '<length>']; }
+
+ +

Nun können wir Typen und Werte der Properties übergeben, was bedeutet: wir können die Anzahl der Pixel und den Typ Nummer direkt verwenden (zugegeben nimmt ctx.lineWidth einen Float als Wert und eigentlich keinen Wert mit Längeneinheiten, aber um des Beispiels willen ...).

+ +
paint(ctx, size, props, args) {
+
+		const strokeWidth = args[1];
+
+		if (strokeWidth.unit === 'px') {
+			ctx.lineWidth = strokeWidth.value;
+		} else {
+			ctx.lineWidth = 1.0;
+		}
+
+	...
+}
+
+ +

Es ist wichtig, hier den Unterschied zwischen selbsterstellten Properties und den Argumenten zu erwähnen. Selbsterstellte Properties (und auch alle Properties für einen bestimmten Selektor) sind global - sie können überall in unserem CSS und JS verwendet werden.

+ +

Wenn Sie zum Beispiel ein --mainColor definiert haben, der dazu dient, eine Farbe mit der Funktion paint() zu setzen, kann dieser auch dazu verwendet werden, anderswo im CSS Farben zu setzen. Wenn Sie diesen Wert speziell für paint ändern wollen, kann sich das als schwierig erweisen. Hier kommt dann das angepasste Argument ins Spiel. Argumente dienen dazu, das zu kontrollieren, was man aktuell zeichnet, während Properties dazu dienen, den Stil zu kontrollieren.

+ +

The list items have a background image that is either pink, purple or green, with different stroke widths, and the green one being filled.

+ +

Nun können wir die Vorteile dieser API sehen: wir können zahlreiche selbsterstellte Properties und Argumente dafür verwenden, um wiederverwendbare und vollkommen kontrollierbare Styling-Funktionen zu erstellen.

+ +
registerPaint('hollowHighlights', class {
+
+  static get inputProperties() { return ['--boxColor']; }
+  // Input arguments that can be passed to the `paint` function
+  static get inputArguments() { return ['*','']; }
+
+  static get contextOptions() { return {alpha: true}; }
+
+  paint(ctx, size, props, args) {
+    // ctx   -> drawing context
+    // size  -> size of the box being painted
+    // props -> list of custom properties available to the element
+	// args  -> list of arguments set when calling the paint() function in the css
+
+		// where to start the highlight & dimensions
+		const x = 0;
+		const y = size.height * 0.3;
+		const blockWidth = size.width * 0.33;
+		const blockHeight = size.height * 0.85;
+
+		// the values passed in the paint() function in the CSS
+		const colour = props.get( '--boxColor' );
+		const strokeType = args[0].toString();
+		const strokeWidth = parseInt(args[1]);
+
+
+		// set the stroke width
+		if ( strokeWidth ) {
+			ctx.lineWidth = strokeWidth;
+		} else {
+			ctx.lineWidth = 1.0;
+		}
+		// set the fill type
+		if ( strokeType === 'stroke' ) {
+			ctx.fillStyle = 'transparent';
+			ctx.strokeStyle = colour;
+		} else if ( strokeType === 'filled' ) {
+			ctx.fillStyle = colour;
+			ctx.strokeStyle = colour;
+		} else {
+			ctx.fillStyle = 'none';
+			ctx.strokeStyle = 'none';
+		}
+
+		// block
+		ctx.beginPath();
+		ctx.moveTo( x, y );
+		ctx.lineTo( blockWidth, y );
+		ctx.lineTo( blockWidth + blockHeight, blockHeight );
+		ctx.lineTo( x, blockHeight );
+		ctx.lineTo( x, y );
+		ctx.closePath();
+		ctx.fill();
+		ctx.stroke();
+		// dashes
+		for (let i = 0; i < 4; i++) {
+			let start = i * 2;
+			ctx.beginPath();
+			ctx.moveTo( blockWidth + (start * 10) + 10, y);
+			ctx.lineTo( blockWidth + (start * 10) + 20, y);
+			ctx.lineTo( blockWidth + (start * 10) + 20 + blockHeight, blockHeight);
+			ctx.lineTo( blockWidth + (start * 10) + 10 + blockHeight, blockHeight);
+			ctx.lineTo( blockWidth + (start * 10) + 10, y);
+			ctx.closePath();
+			ctx.fill();
+			ctx.stroke();
+		}
+
+  } // paint
+});
+
+ +

Wir können verschiedene Farbe und Strichstärken setzen und entscheiden, ob das Hintergrundbild gefüllt oder leer ist:

+ +
+
li {
+   --boxColor: hsla(155, 90%, 60%, 0.5);
+   background-image: paint(hollowHighlights, stroke, 5px);
+}
+
+li:nth-of-type(3n) {
+   --boxColor: hsla(255, 90%, 60%, 0.5);
+   background-image: paint(hollowHighlights, filled,  3px);
+}
+
+li:nth-of-type(3n+1) {
+   --boxColor: hsla(355, 90%, 60%, 0.5);
+   background-image: paint(hollowHighlights, stroke, 1px);
+}
+ + + +

In unserem <script>-Block melden wir das Worklet an:

+ +
CSS.paintWorklet.addModule('https://mdn.github.io/houdini-examples/cssPaint/intro/worklets/hollow.js');
+
+ +

{{EmbedLiveSample("example5", 300, 300)}}

+ +

Siehe auch

+ + diff --git a/files/de/web/api/css_painting_api/index.html b/files/de/web/api/css_painting_api/index.html new file mode 100644 index 0000000000..799979f66b --- /dev/null +++ b/files/de/web/api/css_painting_api/index.html @@ -0,0 +1,199 @@ +--- +title: CSS Painting API +slug: Web/API/CSS_Painting_API +tags: + - API + - CSS + - CSS Paint API + - Houdini + - NeedsTranslation + - Painting + - Reference + - TopicStub +translation_of: Web/API/CSS_Painting_API +--- +
{{DefaultAPISidebar("CSS Painting API")}}
+ +

The CSS Painting API — part of the CSS Houdini umbrella of APIs — allows developers to write JavaScript functions that can draw directly into an element's background, border, or content.

+ +

Concepts and usage

+ +

Essentially, the CSS Painting API contains functionality allowing developers to create custom values for {{cssxref('paint', 'paint()')}}, a CSS <image> function. You can then apply these values to properties like {{cssxref("background-image")}} to set complex custom backgrounds on an element.

+ +

For example:

+ +
aside {
+  background-image: paint(myPaintedImage);
+}
+ +

The API defines {{domxref('PaintWorklet')}}, a {{domxref('worklet')}} that can be used to programmatically generate an image that responds to computed style changes. To find out more about how this is used, consult Using the CSS Painting API.

+ +

Interfaces

+ +
+
{{domxref('PaintWorklet')}}
+
Programmatically generates an image where a CSS property expects a file. Access this interface through CSS.paintWorklet.
+
{{domxref('PaintWorkletGlobalScope')}}
+
The global execution context of the paintWorklet.
+
{{domxref('PaintRenderingContext2D')}}
+
+

Implements a subset of the CanvasRenderingContext2D API. It has an output bitmap that is the size of the object it is rendering to.

+
+
{{domxref('PaintSize')}}
+
Returns the read-only values of the output bitmap's width and height.
+
+ +

Dictionaries

+ +
+
{{domxref('PaintRenderingContext2DSettings')}}
+
A dictionary providing a subset of CanvasRenderingContext2D settings.
+
+ +

Examples

+ +

To draw directly into an element's background using JavaScript in our CSS, we define a paint worklet using the registerPaint() function, tell the document to include the worklet using the paintWorklet addModule() method, then include the image we created using the CSS paint()  function.

+ +

We create our PaintWorklet called 'hollowHighlights' using the registerPaint() function:

+ +
registerPaint('hollowHighlights', class {
+
+  static get inputProperties() { return ['--boxColor']; }
+
+  static get inputArguments() { return ['*','<length>']; }
+
+  static get contextOptions() { return {alpha: true}; }
+
+  paint(ctx, size, props, args) {
+		const x = 0;
+		const y = size.height * 0.3;
+		const blockWidth = size.width * 0.33;
+		const blockHeight = size.height * 0.85;
+
+		const theColor = props.get( '--boxColor' );
+		const strokeType = args[0].toString();
+		const strokeWidth = parseInt(args[1]);
+
+		console.log(theColor);
+
+		if ( strokeWidth ) {
+			ctx.lineWidth = strokeWidth;
+		} else {
+			ctx.lineWidth = 1.0;
+		}
+
+		if ( strokeType === 'stroke' ) {
+			ctx.fillStyle = 'transparent';
+			ctx.strokeStyle = theColor;
+		} else if ( strokeType === 'filled' ) {
+			ctx.fillStyle = theColor;
+			ctx.strokeStyle = theColor;
+		} else {
+			ctx.fillStyle = 'none';
+			ctx.strokeStyle = 'none';
+		}
+
+
+		ctx.beginPath();
+		ctx.moveTo( x, y );
+		ctx.lineTo( blockWidth, y );
+		ctx.lineTo( blockWidth + blockHeight, blockHeight );
+		ctx.lineTo( x, blockHeight );
+		ctx.lineTo( x, y );
+		ctx.closePath();
+		ctx.fill();
+		ctx.stroke();
+
+		for (let i = 0; i < 4; i++) {
+			let start = i * 2;
+			ctx.beginPath();
+			ctx.moveTo( blockWidth + (start * 10) + 10, y);
+			ctx.lineTo( blockWidth + (start * 10) + 20, y);
+			ctx.lineTo( blockWidth + (start * 10) + 20 + blockHeight, blockHeight);
+			ctx.lineTo( blockWidth + (start * 10) + 10 + blockHeight, blockHeight);
+			ctx.lineTo( blockWidth + (start * 10) + 10, y);
+			ctx.closePath();
+			ctx.fill();
+			ctx.stroke();
+		}
+  }
+});
+ +
+

We then include the paintWorklet:

+ + + +
  CSS.paintWorklet.addModule('https://mdn.github.io/houdini-examples/cssPaint/intro/worklets/hilite.js');
+
+ +

Then we can use the {{cssxref('<image>')}} with the CSS {{cssxref('paint()')}} function:

+ +
li {
+   --boxColor: hsla(55, 90%, 60%, 1.0);
+   background-image: paint(hollowHighlights, stroke, 2px);
+}
+
+li:nth-of-type(3n) {
+   --boxColor: hsla(155, 90%, 60%, 1.0);
+   background-image: paint(hollowHighlights, filled,  3px);
+}
+
+li:nth-of-type(3n+1) {
+   --boxColor: hsla(255, 90%, 60%, 1.0);
+   background-image: paint(hollowHighlights, stroke, 1px);
+}
+
+

We've included a custom property in the selector block defining a boxColor. Custom properties are accessible to the PaintWorklet.

+ +

{{EmbedLiveSample("hollowExample", 300, 300)}}

+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS Painting API')}}{{Spec2('CSS Painting API')}}Initial definition.
+ +

Browser compatibility

+ +

See the browser compatibility data for each CSS Painting API Interfaces.

+ +

See Also

+ + diff --git a/files/de/web/api/cssmediarule/index.html b/files/de/web/api/cssmediarule/index.html new file mode 100644 index 0000000000..cf00ea0100 --- /dev/null +++ b/files/de/web/api/cssmediarule/index.html @@ -0,0 +1,120 @@ +--- +title: CSSMediaRule +slug: Web/API/CSSMediaRule +tags: + - API + - CSSOM + - Referenz + - Schnittstelle +translation_of: Web/API/CSSMediaRule +--- +

{{ APIRef("CSSOM") }}

+ +

Die CSSMediaRule ist eine Schnittstelle, die eine einzelne CSS-Regel darstellt. Sie implementiert die {{domxref("CSSConditionRule")}}-Schnittstelle und somit auch die {{domxref("CSSGroupingRule")}}- sowie die {{domxref("CSSRule")}}-Schnittstelle mit einem Typwert von 4 (CSSRule.MEDIA_RULE).

+ +

Syntax

+ +

Die Syntax wird mittels der WebIDL definiert.

+ +
interface CSSMediaRule : CSSConditionRule {
+    readonly attribute MediaList media;
+}
+
+ +

Eigenschaften

+ +

Als eine {{ domxref("CSSConditionRule") }}, und somit der {{domxref("CSSGroupingRule")}} und {{ domxref("CSSRule") }}, implementiert die CSSMediaRule auch gleichzeitig die Eigenschaften dieser Schnittstellen. Darüber hinaus hat sie die folgende spezielle Eigenschaft:

+ +
+
{{domxref("CSSMediaRule.media")}} {{readonlyinline()}}
+
Definiert {{domxref("MediaList")}}, welches das zugedachte Zielmedium für die Style-Informationen wiedergibt.
+
+ +

Methoden

+ +

Wie eine {{ domxref("CSSConditionRule") }} und daher eine {{domxref("CSSGroupingRule")}} als auch eine {{ domxref("CSSRule") }}, implementiert CSSMediaRule auch die Methoden dieser Schnittstelle. Sie selbst hat keine speziellen Methoden.

+ +

Spezifikationen

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
SpezifikationStatusKommentar
{{ SpecName('CSS3 Conditional', '#the-cssmediarule-interface', 'CSSMediaRule') }}{{ Spec2('CSS3 Conditional')}}Als Ableitung von  {{domxref("CSSConditionRule")}}.
{{ SpecName('CSSOM', '#the-cssmediarule-interface', 'CSSMediaRule') }}{{ Spec2('CSSOM') }}Keine Abweichungen von  {{SpecName('DOM2 Style')}}
{{SpecName('DOM2 Style', 'css.html#CSS-CSSMediaRule', 'CSSMediaRule') }}{{ Spec2('DOM2 Style') }} 
+ +

Browser Kompatibilität 

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
MerkmalChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Grundlegende Unterstützung{{ CompatChrome(45.0) }}{{ CompatVersionUnknown }} [1]{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
MerkmalAndroidAndroid WebviewFirefox Mobile (Gecko)IE PhoneOpera MobileSafari MobileChrome for Android
Grundlegende Unterstützung{{ CompatUnknown() }}{{ CompatChrome(45.0) }}{{ CompatGeckoMobile("17") }} [1]{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatChrome(45.0) }}
+
+ +

[1] Das Setzen des Werts von conditionText in Gecko ist nur ab Firefox 20 möglich.

diff --git a/files/de/web/api/csspagerule/index.html b/files/de/web/api/csspagerule/index.html new file mode 100644 index 0000000000..c6a30fc95e --- /dev/null +++ b/files/de/web/api/csspagerule/index.html @@ -0,0 +1,129 @@ +--- +title: CSSPageRule +slug: Web/API/CSSPageRule +tags: + - API + - CSSOM + - Referenz +translation_of: Web/API/CSSPageRule +--- +

{{ APIRef("CSSOM") }}

+ +

Übersicht

+ +

CSSPageRule ist eine Schnittstelle, die eine einzelne CSS {{cssxref("@page")}} Regel repräsentiert. Sie implementiert die {{domxref("CSSRule")}} Schnittstelle mit dem Typwert 6 (CSSRule.PAGE_RULE).

+ +

Syntax

+ +

Die Syntax wird im WebIDL Format beschrieben.

+ +
interface CSSPageRule : CSSRule {
+    attribute DOMString selectorText;
+    readonly attribute CSSStyleDeclaration style;
+};
+
+ +

Eigenschaften

+ +

Als eine {{ domxref("CSSRule") }} implementiert CSSPageRule auch die Eigenschaften dieser Schnittstelle. Sie hat die folgenden speziellen Eigenschaften:

+ +
+
{{domxref("CSSPageRule.selectorText")}}
+
Repräsentiert den Text eines zur At-Regel gehörenden Seitenselektors.
+
{{domxref("CSSPageRule.style")}} {{readonlyinline()}}
+
Gibt den zur At-Regel gehörenden Deklarationsblock zurück.
+
+ +

Methoden

+ +

Als eine {{ domxref("CSSRule") }} implementiert CSSPageRule auch die Methoden dieser Schnittstelle. Sie hat keine speziellen Methoden.

+ +

Spezifikationen

+ + + + + + + + + + + + + + + + + + + + + +
SpezifikationStatusAnmerkung
{{ SpecName('CSSOM', '#the-csspagerule-interface', 'CSSPageRule') }}{{ Spec2('CSSOM') }}Keine Änderungen bezüglich {{SpecName('DOM2 Style')}}
{{SpecName('DOM2 Style', 'css.html#CSS-CSSPageRule', 'CSSPageRule') }}{{ Spec2('DOM2 Style') }} 
+ +

Browser Kompatibilität

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
MerkmalChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Grundlegende Unterstützung{{ CompatVersionUnknown }}{{ CompatGeckoDesktop("19") }}{{ CompatVersionUnknown }}{{ CompatVersionUnknown }}{{ CompatVersionUnknown }}
selectorText{{ CompatVersionUnknown }}{{CompatNo}}{{ CompatVersionUnknown }}{{ CompatVersionUnknown }}{{ CompatVersionUnknown }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
MerkmalAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Grundlegende Unterstützung{{ CompatUnknown() }}{{ CompatGeckoMobile("19") }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
selectorText{{ CompatUnknown() }}{{CompatNo}}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
diff --git a/files/de/web/api/cssrule/csstext/index.html b/files/de/web/api/cssrule/csstext/index.html new file mode 100644 index 0000000000..789cd7519a --- /dev/null +++ b/files/de/web/api/cssrule/csstext/index.html @@ -0,0 +1,31 @@ +--- +title: CSSRule.cssText +slug: Web/API/CSSRule/cssText +tags: + - API + - CSSOM + - Eigenschaft + - Referenz +translation_of: Web/API/CSSRule/cssText +--- +
+ {{ APIRef() }}
+

Übersicht

+

cssText gibt den eigentlichen Text der Styleregel zurück. Um eine Stylesheet Regel dynamisch setzen zu können, siehe Dynamische Stylinginformationen verwenden.

+

Syntax

+
string = cssRule.cssText
+
+

Beispiel

+
<style>
+body { background-color: darkblue; }
+</style>
+<script>
+  var stylesheet = document.styleSheets[0];
+  alert(stylesheet.cssRules[0].cssText); // body { background-color: darkblue; }
+</script>
+
+
+

Spezifikation

+ diff --git a/files/de/web/api/cssrule/index.html b/files/de/web/api/cssrule/index.html new file mode 100644 index 0000000000..eeca8828cf --- /dev/null +++ b/files/de/web/api/cssrule/index.html @@ -0,0 +1,258 @@ +--- +title: CSSRule +slug: Web/API/CSSRule +tags: + - CSSOM +translation_of: Web/API/CSSRule +--- +
{{APIRef("CSSOM")}}
+ +

An object implementing the CSSRule DOM interface represents a single CSS at-rule. References to a CSSRule-implementing object may be obtained by looking at a CSS style sheet's {{domxref("CSSStyleSheet","cssRules")}} list.

+ +

There are several kinds of rules. The CSSRule interface specifies the properties common to all rules, while properties unique to specific rule types are specified in the more specialized interfaces for those rules' respective types.

+ +

Syntax

+ +

The syntax is described using the WebIDL format.

+ +
interface CSSRule {
+    const unsigned short STYLE_RULE = 1;
+    const unsigned short CHARSET_RULE = 2;
+    const unsigned short IMPORT_RULE = 3;
+    const unsigned short MEDIA_RULE = 4;
+    const unsigned short FONT_FACE_RULE = 5;
+    const unsigned short PAGE_RULE = 6;
+    const unsigned short KEYFRAMES_RULE = 7;
+    const unsigned short KEYFRAME_RULE = 8;
+    const unsigned short NAMESPACE_RULE = 10;
+    const unsigned short COUNTER_STYLE_RULE = 11;
+    const unsigned short SUPPORTS_RULE = 12;
+    const unsigned short DOCUMENT_RULE = 13;
+    const unsigned short FONT_FEATURE_VALUES_RULE = 14;
+    const unsigned short VIEWPORT_RULE = 15;
+    const unsigned short REGION_STYLE_RULE = 16;
+    readonly attribute unsigned short type;
+    attribute DOMString cssText;
+    readonly attribute CSSRule? parentRule;
+    readonly attribute CSSStyleSheet? parentStyleSheet;
+};
+ +

Properties common to all CSSRule instances

+ +
+
{{domxref("CSSRule.cssText")}}
+
Represents the textual representation of the rule, e.g. "h1,h2 { font-size: 16pt }"
+
{{domxref("CSSRule.parentRule")}} {{readonlyinline}}
+
Returns the containing rule, otherwise null. E.g. if this rule is a style rule inside an {{cssxref("@media")}} block, the parent rule would be that {{domxref("CSSMediaRule")}}.
+
{{domxref("CSSRule.parentStyleSheet")}} {{readonlyinline}}
+
Returns the {{domxref("CSSStyleSheet")}} object for the style sheet that contains this rule
+
{{domxref("CSSRule.type")}} {{readonlyinline}}
+
One of the {{anch("Type constants")}} indicating the type of CSS rule.
+
+ +

Constants

+ +

Type constants

+ +

The CSSRule interface specifies integer constants that can be used in conjunction with a CSSRule's {{domxref("cssRule/type","type")}} property to discern the rule type (and therefore, which specialized interface it implements). The relationships between these constants and the interfaces are:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
TypeValueRule-specific interface
CSSRule.STYLE_RULE1{{domxref("CSSStyleRule")}}
CSSRule.MEDIA_RULE4{{domxref("CSSMediaRule")}}
CSSRule.FONT_FACE_RULE5{{domxref("CSSFontFaceRule")}}
CSSRule.PAGE_RULE6{{domxref("CSSPageRule")}}
CSSRule.IMPORT_RULE3{{domxref("CSSImportRule")}} : IDL: nsIDOMCSSImportRule
CSSRule.CHARSET_RULE2{{domxref("CSSCharsetRule")}} {{obsolete_inline}}
CSSRule.UNKNOWN_RULE0{{domxref("CSSUnknownRule")}}{{obsolete_inline}}
CSSRule.KEYFRAMES_RULE7{{domxref("CSSKeyframesRule")}} [1] {{experimental_inline}}
CSSRule.KEYFRAME_RULE8{{domxref("CSSKeyframeRule")}} [1] {{experimental_inline}}
Reserved for future use9Should be used to define color profiles in the future
CSSRule.NAMESPACE_RULE10{{domxref("CSSNamespaceRule")}} {{experimental_inline}}
CSSRule.COUNTER_STYLE_RULE11{{domxref("CSSCounterStyleRule")}} {{experimental_inline}}
CSSRule.SUPPORTS_RULE12{{domxref("CSSSupportsRule")}}
CSSRule.DOCUMENT_RULE13{{domxref("CSSDocumentRule")}} {{experimental_inline}}
CSSRule.FONT_FEATURE_VALUES_RULE14{{domxref("CSSFontFeatureValuesRule")}}
CSSRule.VIEWPORT_RULE15{{domxref("CSSViewportRule")}} {{experimental_inline}}
CSSRule.REGION_STYLE_RULE16{{domxref("CSSRegionStyleRule")}} {{experimental_inline}}
+ +

An up-to-date informal list of constants can be found on the CSSWG Wiki.

+ +

[1] On Gecko, before Firefox 19, the keyframe-related constants existed only in their prefixed version: CSSRule.MOZ_KEYFRAMES_RULE and CSSRule.MOZ_KEYFRAME_RULE. From Firefox 20 onwards, both versions are available. The prefixed version will be removed in the future.

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSSOM', '#css-rules', 'CSSRule')}}{{Spec2('CSSOM')}}Obsoleted values CHARSET_RULE and UNKNOWN_RULE. Added value NAMESPACE_RULE.
{{SpecName("CSS3 Animations",'#cssrule', 'CSSRule')}}{{Spec2('CSS3 Animations')}}Added values KEYFRAMES_RULE and KEYFRAME_RULE.
{{SpecName('CSS3 Fonts', '#om-fontfeaturevalues', 'CSSRule')}}{{Spec2('CSS3 Fonts')}}Added value FONT_FEATURE_VALUES_RULE.
{{SpecName("CSS3 Counter Styles", "#extentions-to-cssrule-interface", 'CSSRule')}}{{Spec2("CSS3 Counter Styles")}}Added value COUNTER_STYLE_RULE.
{{SpecName("CSS3 Conditional", '#extentions-to-cssrule-interface', 'CSSRule')}}{{Spec2('CSS3 Conditional')}}Added value SUPPORTS_RULE. (DOCUMENT_RULE has been pushed to CSS Conditional Rules Level 4)
{{SpecName('DOM2 Style', 'css.html#CSS-CSSRule', 'CSSRule')}}{{Spec2('DOM2 Style')}}Initial definition.
+ +

Browser compatibility

+ +

To get browser compatibility information about the different type constant value, please consult the compatibility table of the associated interface.

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}9{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

See also

+ + diff --git a/files/de/web/api/customelementregistry/define/index.html b/files/de/web/api/customelementregistry/define/index.html new file mode 100644 index 0000000000..b51ed46c37 --- /dev/null +++ b/files/de/web/api/customelementregistry/define/index.html @@ -0,0 +1,241 @@ +--- +title: CustomElementRegistry.define() +slug: Web/API/CustomElementRegistry/define +tags: + - API + - CustomElementRegistry + - Method + - Reference + - Web Components + - Webkomponente + - benutzerdefiniert + - custom elements + - define +translation_of: Web/API/CustomElementRegistry/define +--- +

{{APIRef("CustomElementRegistry")}}

+ +

Die define() Methode der {{domxref("CustomElementRegistry")}} Schnittstelle beschreibt ein neues benutzerdefiniertes Element.

+ +

Es gibt zwei Arten von benutzerdefinierten Elementen, die erstellt werden können:

+ + + +

Syntax

+ +
customElements.define(name, constructor, options);
+
+ +

Parameter

+ +
+
name
+
Name des neuen benutzerdefinierten Elements. Beachte, dass Namen von benutzerdefinierten Elementen einen Bindestrich enthalten müssen.
+
constructor
+
Konstruktor für das neue, benutzerdefinierte Element.
+
options {{optional_inline}}
+
Objekt, das steuert, wie das Element definiert ist. Eine Option wird derzeit unterstützt: +
    +
  • extends: String des Namens eines integrierten Elements das erweitert werden soll. Wird verwendet um ein angepasstes integriertes Element  zu erzeugen.
  • +
+
+
+ +

Return value

+ +

Void.

+ +

Ausnahmebehandlung

+ + + + + + + + + + + + + + + + + + + + + + +
ExceptionDescription
NotSupportedError +

Das {{domxref("CustomElementRegistry")}} enthält bereits einen Eintrag mit dem gleichen Namen oder dem gleichen Konstruktor (oder ist auf andere Weise bereits definiert), oder extends ist angegeben und es ist ein gültiger benutzerdefinierter Elementname oder extends ist angegeben, aber das Element, das es zu erweitern versucht, ist ein unbekanntes Element.

+
SyntaxErrorDer angegebene Name ist kein gültiger benutzerdefinierter Elementname.
TypeErrorDer referenzierte Konstruktor ist kein Konstruktor.
+ +
+

Hinweis: Du wirst oftmals  NotSupportedErrors geworfen bekommen, die so erscheinen als würde define() fehlschlagen, aber stattdessen wahrscheinlich ein Problem mit {domxref("Element.attachShadow()")}} sind.

+
+ +

Beispiele

+ +

Autonomes benutzerdefiniertes Element

+ +

Der folgende Code entstammt dem popup-info-box-web-component Beispiel (siehe Live).

+ +
// Create a class for the element
+class PopUpInfo extends HTMLElement {
+  constructor() {
+    // Always call super first in constructor
+    super();
+
+    // Create a shadow root
+    var shadow = this.attachShadow({mode: 'open'});
+
+    // Create spans
+    var wrapper = document.createElement('span');
+    wrapper.setAttribute('class','wrapper');
+    var icon = document.createElement('span');
+    icon.setAttribute('class','icon');
+    icon.setAttribute('tabindex', 0);
+    var info = document.createElement('span');
+    info.setAttribute('class','info');
+
+    // Take attribute content and put it inside the info span
+    var text = this.getAttribute('text');
+    info.textContent = text;
+
+    // Insert icon
+    var imgUrl;
+    if(this.hasAttribute('img')) {
+      imgUrl = this.getAttribute('img');
+    } else {
+      imgUrl = 'img/default.png';
+    }
+    var img = document.createElement('img');
+    img.src = imgUrl;
+    icon.appendChild(img);
+
+    // Create some CSS to apply to the shadow dom
+    var style = document.createElement('style');
+
+    style.textContent = '.wrapper {' +
+                           'position: relative;' +
+                        '}' +
+
+                         '.info {' +
+                            'font-size: 0.8rem;' +
+                            'width: 200px;' +
+                            'display: inline-block;' +
+                            'border: 1px solid black;' +
+                            'padding: 10px;' +
+                            'background: white;' +
+                            'border-radius: 10px;' +
+                            'opacity: 0;' +
+                            'transition: 0.6s all;' +
+                            'position: absolute;' +
+                            'bottom: 20px;' +
+                            'left: 10px;' +
+                            'z-index: 3;' +
+                          '}' +
+
+                          'img {' +
+                            'width: 1.2rem' +
+                          '}' +
+
+                          '.icon:hover + .info, .icon:focus + .info {' +
+                            'opacity: 1;' +
+                          '}';
+
+    // attach the created elements to the shadow dom
+
+    shadow.appendChild(style);
+    shadow.appendChild(wrapper);
+    wrapper.appendChild(icon);
+    wrapper.appendChild(info);
+  }
+}
+
+// Define the new element
+customElements.define('popup-info', PopUpInfo);
+
+ +
<popup-info img="img/alt.png" text="Your card validation code (CVC) is an extra
+                                    security feature — it is the last 3 or 4
+                                    numbers on the back of your card.">
+ +
+

Hinweis: Konstruktoren für autonome benutzerdefinierte Elemente müssen {{domxref("HTMLElement")}} extenden.

+
+ +

Benutzerdefiniertes integriertes Element

+ +

Der folgende Code entstammt dem word-count-web-component Beispiel (siehe Live).

+ +
// Create a class for the element
+class WordCount extends HTMLParagraphElement {
+  constructor() {
+    // Always call super first in constructor
+    super();
+
+    // count words in element's parent element
+    var wcParent = this.parentNode;
+
+    function countWords(node){
+      var text = node.innerText || node.textContent
+      return text.split(/\s+/g).length;
+    }
+
+    var count = 'Words: ' + countWords(wcParent);
+
+    // Create a shadow root
+    var shadow = this.attachShadow({mode: 'open'});
+
+    // Create text node and add word count to it
+    var text = document.createElement('span');
+    text.textContent = count;
+
+    // Append it to the shadow root
+    shadow.appendChild(text);
+
+
+    // Update count when element content changes
+    setInterval(function() {
+      var count = 'Words: ' + countWords(wcParent);
+      text.textContent = count;
+    }, 200)
+
+  }
+}
+
+// Define the new element
+customElements.define('word-count', WordCount, { extends: 'p' });
+ +
<p is="word-count"></p>
+ +

Spezifikationen

+ + + + + + + + + + + + + + +
SpezifikationStatusKommentar
{{SpecName("HTML WHATWG", "custom-elements.html#dom-customelementregistry-define", "customElements.define()")}}{{Spec2("HTML WHATWG")}}Initial definition.
+ +

Browserkompatibilität

+ +
+ + +

{{Compat("api.CustomElementRegistry.define")}}

+
diff --git a/files/de/web/api/customelementregistry/index.html b/files/de/web/api/customelementregistry/index.html new file mode 100644 index 0000000000..db8bc5b464 --- /dev/null +++ b/files/de/web/api/customelementregistry/index.html @@ -0,0 +1,106 @@ +--- +title: CustomElementRegistry +slug: Web/API/CustomElementRegistry +tags: + - API + - CustomElementRegistry + - Experimental + - Interface + - Landing + - NeedsTranslation + - Reference + - TopicStub + - Web Components + - custom elements +translation_of: Web/API/CustomElementRegistry +--- +

{{DefaultAPISidebar("Web Components")}}

+ +

The CustomElementRegistry interface provides methods for registering custom elements and querying registered elements. To get an instance of it, use the {{domxref("window.customElements")}} property. 

+ +

Methods

+ +
+
{{domxref("CustomElementRegistry.define()")}}
+
Defines a new custom element.
+
{{domxref("CustomElementRegistry.get()")}}
+
Returns the constuctor for the named custom element, or undefined if the custom element is not defined.
+
{{domxref("CustomElementRegistry.upgrade()")}}
+
Upgrades a custom element directly, even before it is connected to its shadow root.
+
{{domxref("CustomElementRegistry.whenDefined()")}}
+
Returns an empty {{jsxref("Promise", "promise")}} that resolves when a custom element becomes defined with the given name. If such a custom element is already defined, the returned promise is immediately fulfilled.
+
+ +

Examples

+ +

The following code is taken from our word-count-web-component example (see it live also). Note how we use the {{domxref("CustomElementRegistry.define()")}} method to define the custom element after creating its class.

+ +
// Create a class for the element
+class WordCount extends HTMLParagraphElement {
+  constructor() {
+    // Always call super first in constructor
+    super();
+
+    // count words in element's parent element
+    var wcParent = this.parentNode;
+
+    function countWords(node){
+      var text = node.innerText || node.textContent
+      return text.split(/\s+/g).length;
+    }
+
+    var count = 'Words: ' + countWords(wcParent);
+
+    // Create a shadow root
+    var shadow = this.attachShadow({mode: 'open'});
+
+    // Create text node and add word count to it
+    var text = document.createElement('span');
+    text.textContent = count;
+
+    // Append it to the shadow root
+    shadow.appendChild(text);
+
+
+    // Update count when element content changes
+    setInterval(function() {
+      var count = 'Words: ' + countWords(wcParent);
+      text.textContent = count;
+    }, 200)
+
+  }
+}
+
+// Define the new element
+customElements.define('word-count', WordCount, { extends: 'p' });
+ +
+

Note: The CustomElementRegistry is available through the {{domxref("Window.customElements")}} property.

+
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("HTML WHATWG", "custom-elements.html#customelementregistry", "CustomElementRegistry")}}{{Spec2("HTML WHATWG")}}Initial definition.
+ +

Browser compatibility

+ +

 

+ + + +

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

+ +

 

diff --git a/files/de/web/api/dedicatedworkerglobalscope/index.html b/files/de/web/api/dedicatedworkerglobalscope/index.html new file mode 100644 index 0000000000..2aaef1f2e7 --- /dev/null +++ b/files/de/web/api/dedicatedworkerglobalscope/index.html @@ -0,0 +1,114 @@ +--- +title: DedicatedWorkerGlobalScope +slug: Web/API/DedicatedWorkerGlobalScope +translation_of: Web/API/DedicatedWorkerGlobalScope +--- +

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

+ +

Auf das DedicatedWorkerGlobalScope Objekt (Der globale Scope des {{domxref("Worker")}}) kann durch das Schlüsselwort {{domxref("window.self","self")}} zugegriffen werden. Einzelne weitere globale Funktionen, namespace Objekte und Konstruktoren, die nicht typischerweise mit dem Scope des Workers in Verbindung stehen, jedoch darauf verfügbar sind, können in der JavaScript Reference gefunden werden. Siehe auch: Functions available to workers.

+ +

Eigenschaften

+ +

Dieses Interface erbt seine Eigenschaften aus dem Interface {{domxref("WorkerGlobalScope")}} und seinem übergeordneten Interface {{domxref("EventTarget")}}. Deshalbt implementiert es die Eigenschaften {{domxref("WindowTimers")}}, {{domxref("WindowBase64")}}, und {{domxref("WindowEventHandlers")}}.

+ +
+
{{domxref("DedicatedWorkerGlobalScope.name")}} {{readOnlyinline}}
+
Der dem {{domxref("Worker")}} (optional) gegebene Name, als er im Konstruktor {{domxref("Worker.Worker", "Worker()")}} erzeugt wurde. Hauptsächlich nützlich für Debuggin.
+
+ +

Von WorkerGlobal Scope geerbte Eigenschaften

+ +
+
{{domxref("WorkerGlobalScope.self")}}
+
Gibt eine Objektreferenz auf das DedicatedWorkerGlobalScope Objekt selbst zurück.
+
{{domxref("WorkerGlobalScope.console")}} {{readOnlyinline}}
+
Gibt das mit dem Worker verbundene {{domxref("Console")}} Objekt zurück.
+
{{domxref("WorkerGlobalScope.location")}} {{readOnlyinline}}
+
Gibt das mit dem Worker verbundene {{domxref("WorkerLocation")}} Objekt zurück. Bei WorkerLocation handelt es sich um ein spezifisches location Objekt, welches aus Teilen des {{domxref("Location")}} Objekts des Browserscope besteht,  jedoch für den Worker angepasst wurde.
+
{{domxref("WorkerGlobalScope.navigator")}} {{readOnlyinline}}
+
Git das mit dem Worker verbundene {{domxref("WorkerNavigator")}} Objekt  zurück. Bei WorkerNavigator handelt es sich um ein spezifisches navigations Objekt, welches aus Teilen des {{domxref("Navigator")}} Objekts des Browserscope besteht, jedoch für den Worker angepasst wurde.
+
{{domxref("WorkerGlobalScope.performance")}} {{readOnlyinline}} {{Non-standard_inline}}
+
Git das mit dem Worker verbunde {{domxref("Performance")}} Objekt zurück. Dabei handelt es sich um ein reguläres performance Objekt,  welches jedoch nur teile der Eigenschaften und Methoden umfasst.
+
+ +

Eventhandler

+ +

Dieses Interface erbt seine Eventhandler  aus dem Interface {domxref("WorkerGlobalScope")}} und seinen übergeordneten Interface {{domxref("EventTarget")}}. Deshalb sind Eventhandler {{domxref("WindowTimers")}}, {{domxref("WindowBase64")}}, und {{domxref("WindowEventHandlers")}} implementiert.

+ +
+
{{domxref("DedicatedWorkerGlobalScope.onmessage")}}
+
Der entsprechende Code eines {{domxref("EventHandler")}} der beim Aufruf des Events {{event("message")}} aufgerufen wird. Diese Events sind vom Typ {{domxref("MessageEvent")}} und werden aufgerufen, wenn der Worker eine Nachricht aus dem Dokument erhält, welcher Ihn gestartet hat (Beispiel: {{domxref("Worker.postMessage")}} Methode.) 
+
{{domxref("DedicatedWorkerGlobalScope.onmessageerror")}}
+
Der entsprechende Code eines {{domxref("EventHandler")}} der beim Aufruf des Events {{event("messageerror")}} aufgerufen wird.
+
+ +

Methoden

+ +

Dieses Interface erbt seine Methoden aus dem Interface {{domxref("WorkerGlobalScope")}} und seinen übergordneten Interface {{domxref("EventTarget")}}. Dementsprechend implementiert es Methoden von {{domxref("WindowTimers")}}, {{domxref("WindowBase64")}}, und {{domxref("WindowEventHandlers")}}.

+ +
+
{{domxref("DedicatedWorkerGlobalScope.close()")}}
+
Verwirft alle im WorkerGlobalScope's Eventloop eingereihten Aufgaben und schließt den entsprechenden Scope.
+
{{domxref("DedicatedWorkerGlobalScope.postMessage()")}}
+
Sendet eine Nachricht — welche aus Javascript Objecten vom Typ any bestehen — zum übergeordneten Dokument, welches den Worker gestartet hat.
+
+ +

Geerbt vom WorkerGlobalScope

+ +
+
{{domxref("WorkerGlobalScope.dump()")}} {{non-standard_inline}}
+
Gibt eine Nachricht in der Konsole aus.
+
{{domxref("WorkerGlobalScope.importScripts()")}}
+
Importiert ein oder mehrere Skripte in den Worker Scope. Es ist möglich beliebig viele, durch Kommas getrennt, zu spezifizieren. Beispiel: importScripts('foo.js', 'bar.js');
+
+ +

Aus verschiedenen Orten implementiert

+ +
+
{{domxref("WindowBase64.atob()")}}
+
Dekodiert einen String von Daten welcher mit base-64 codiert wurde.
+
{{domxref("WindowBase64.btoa()")}}
+
Erzeugt einen base-64 codierten ASCII String aus einem String von Binärdaten.
+
{{domxref("WindowTimers.clearInterval()")}}
+
Bricht die wiederholte Ausführung mit {{domxref("WindowTimers.setInterval()")}} ab.
+
{{domxref("WindowTimers.clearTimeout()")}}
+
Bricht die wiederholte Ausführung mit {{domxref("WindowTimers.setTimeout()")}} ab.
+
{{domxref("WindowTimers.setInterval()")}}
+
Plant die Ausführung einer Funktion alle X Millisekunden
+
{{domxref("WindowTimers.setTimeout()")}}
+
Setzt eine X Millisekunden Verzögerung für die Ausführung einer Funktion
+
+ +

Spezifikationen

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#dedicatedworkerglobalscope', 'DedicatedWorkerGlobalScope')}}{{Spec2('HTML WHATWG')}} 
+ +

Browser Kompatibilität

+ +
+ + +

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

+
+ +

Siehe auch

+ + diff --git a/files/de/web/api/dedicatedworkerglobalscope/message_event/index.html b/files/de/web/api/dedicatedworkerglobalscope/message_event/index.html new file mode 100644 index 0000000000..8e457d414a --- /dev/null +++ b/files/de/web/api/dedicatedworkerglobalscope/message_event/index.html @@ -0,0 +1,83 @@ +--- +title: 'DedicatedWorkerGlobalScope: message event' +slug: Web/API/DedicatedWorkerGlobalScope/message_event +translation_of: Web/API/DedicatedWorkerGlobalScope/message_event +--- +
{{APIRef}}
+ +

Das messageEreignis wird auf ein DedicatedWorkerGlobalScopeObjekt ausgelöst, wenn der Worker eine Nachricht von seinem übergeordneten Objekt empfängt (dh wenn der übergeordnete Benutzer eine Nachricht sendet mit Worker.postMessage()).

+ + + + + + + + + + + + + + + + + + + + +
BubblesNo
CancelableNo
Interface{{domxref("MessageEvent")}}
Event handler propertyonmessage
+ +

Examples

+ +

Dieser Code erstellt einen neuen Worker und sendet ihm eine Nachricht mit Worker.postMessage():

+ +
const worker = new Worker("static/scripts/worker.js");
+
+worker.addEventListener('message', (event) => {
+    console.log(`Received message from worker: ${event.data}`)
+});
+ +

Der Worker kann auf diese Nachricht warten, indem er addEventListener() verwendet:

+ +
// inside static/scripts/worker.js
+
+self.addEventListener('message', (event) => {
+    console.log(`Received message from parent: ${event.data}`);
+});
+ +

Alternativ könnte er es mit der onmessage Event-Handler-Eigenschaft abhören:

+ +
// static/scripts/worker.js
+
+self.onmessage = (event) => {
+    console.log(`Received message from parent: ${event.data}`);
+};
+ +

Specifications

+ + + + + + + + + + + + +
SpecificationStatus
{{SpecName('HTML WHATWG', 'indices.html#event-message')}}{{Spec2('HTML WHATWG')}}
+ +

Browser compatibility

+ + + +

{{Compat("api.DedicatedWorkerGlobalScope.message_event")}}

+ +

See also

+ + diff --git a/files/de/web/api/document/adoptnode/index.html b/files/de/web/api/document/adoptnode/index.html new file mode 100644 index 0000000000..c996e689c5 --- /dev/null +++ b/files/de/web/api/document/adoptnode/index.html @@ -0,0 +1,53 @@ +--- +title: Document.adoptNode() +slug: Web/API/Document/adoptNode +translation_of: Web/API/Document/adoptNode +--- +
{{ ApiRef("DOM") }}
+ +
 
+ +

Überträgt einen Knoten. Der Knoten und sein Unterbaum werden aus dem Dokument, in dem sie sich befinden entfernt (so vorhanden), und sein ownerDocument wird zu dem aktuellen Dokument geändert. Der Knoten kann dann in das aktuelle Dokument eingefügt werden.

+ +

Unterstützt seit Gecko 1.9 (Firefox 3)

+ +

Syntax

+ +
knoten = document.adoptNode(externerKnoten);
+
+ +
+
   knoten
+
Ist der übertragene Knoten, welcher nun dieses Dokument als sein ownerDocument hat.  Der Elternknoten (parentNode) is null, da er noch nicht in den Dokumentenbaum eingefügt wurde. Zu beachten ist, dass knoten und externerKnoten nach dem Funktionsaufruf das gleiche Objekt sind.  
+
externerKnoten
+
Ist der Knoten eines anderes Dokumentes, der übertragen werden soll.
+
+ +

Beispiel

+ +

{{todo}}

+ +

Anmerkungen

+ +

Es kann oassieren, dass der Aufruf von adoptNode fehlschlägt, wenn der Ursprungsknoten von einer anderen Implementierung kommt, was aber bei Browser-Implementierungen kein Problem darstellen sollte.

+ + +

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.

+ +

Spezifikation

+ + + +

Siehe auch

+ + diff --git a/files/de/web/api/document/alinkcolor/index.html b/files/de/web/api/document/alinkcolor/index.html new file mode 100644 index 0000000000..0c656de5cc --- /dev/null +++ b/files/de/web/api/document/alinkcolor/index.html @@ -0,0 +1,30 @@ +--- +title: Document.alinkColor +slug: Web/API/Document/alinkColor +translation_of: Web/API/Document/alinkColor +--- +

{{APIRef("DOM")}} {{ Deprecated_header() }}

+ +

Gibt das Farbattribut eines aktiven Links im Dokumenten body wieder oder setzt es. Ein Link wird in der Zeit eines mousedown und mouseup Events als "aktiv" bezeichnet .

+ +

Syntax

+ +
color = document.alinkColor
+document.alinkColor =color
+
+ +

color ist ein String der den Namen der Farbe (z.B., "blue", "darkblue", etc.) oder  den Hexadezimalwert der Farbe(z.B., #0000FF) enthält. Die Farben samt zugehöriger Hexadezimalcodes können zum Teil hier oder auf ähnlichen Seiten eingesehen werden: https://html-color-codes.info/

+ +

Anmerkungen

+ +

Der Default Wert dieser Eigenschaft in Mozilla Firefox ist rot (#ee0000 in hexadezimal).

+ +

document.alinkColor ist laut DOM Level 2 HTML veraltet. Eine Alternative wäre der CSS Selektor {{ Cssxref(":active") }}.

+ +

Eine weitere Alternative ist document.body.aLink, obwohl diese laut HTML 4.01 ebenfalls veraltet ist und der CSS Selektor präferiert wird.

+ +

Gecko unterstützt sowohl alinkColor/:active als auch{{ Cssxref(":focus") }}. Der Internet Explorer 6 und 7 unterstützen lediglich alinkColor/:active für HTML anchor (<a>) links und verhält sich ähnlich wie :focus bei Gecko. :focus wird im IE nicht unterstützt.

+ +

Browser compatibility

+ +

{{Compat("api.Document.alinkColor")}}

diff --git a/files/de/web/api/document/body/index.html b/files/de/web/api/document/body/index.html new file mode 100644 index 0000000000..cc546cb0ae --- /dev/null +++ b/files/de/web/api/document/body/index.html @@ -0,0 +1,140 @@ +--- +title: Document.body +slug: Web/API/Document/body +translation_of: Web/API/Document/body +--- +
{{APIRef("DOM")}}
+ +

Gibt den {{HTMLElement("body")}} oder {{HTMLElement("frameset")}} Knoten des aktuellen Dokuments wieder, oder null falls keines dieser Elemente existiert.

+ +

Syntax

+ +
var objRef = document.body;
+document.body = objRef;
+ +

Beispiel

+ +
// in 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"
+
+ +

Anmerkungen

+ +

document.body ist das Element, welches den Inhalt eines Dokuments enthält. In Dokumenten mit <body> Inhalt, gibt das <body> Element den Inhalt aus, in Frameset Dokumenten wiederum, wird das äußerste <frameset> Element ausgegeben.

+ +

Da body setzbar ist, wird das Setzen eines neuen Body Elements alle aktuellen Elemente des existierenden <body> Elements entfernen.

+ +

Spezifikation

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpezifikationStatusKommentar
{{SpecName('HTML WHATWG','dom.html#dom-document-body','Document.body')}}{{Spec2('HTML WHATWG')}} 
{{SpecName('HTML5.1','dom.html#dom-document-body','Document.body')}}{{Spec2('HTML5.1')}} 
{{SpecName('HTML5 W3C','dom.html#dom-document-body','Document.body')}}{{Spec2('HTML5 W3C')}} 
{{SpecName('DOM2 HTML','html.html#ID-56360201','Document.body')}}{{Spec2('DOM2 HTML')}} 
{{SpecName('DOM1','level-one-html.html#attribute-body','Document.body')}}{{Spec2('DOM1')}}Initiale Definition.
+ +

Browser Kompatibilität

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support1{{CompatVersionUnknown}}269.6 (möglicherweise früher)4 (möglicherweise früher)
+
+ +
+

 

+ +
+
    +
  1. +

    Obwohl document.body eine sehr gute Methode ist, um das <body> Element in HTML anzusprechen, wird es von Firefox nicht unterstützt, wenn der Content-Type nicht text/html oder application/xhtml+xml ist. Eine sicherere Methode um das <body> Element anzusprechen ist es, document.getElementsByTagName("body") zu verwenden, welches einen Array mit einem einzigen Item ausgibt. Das ist übertragbar auf HTML und XHTML. Bei denen ist der Content-Type nicht im HTTP response header angegeben.

    +
  2. +
+
+ +

 

+ + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}5 (probably earlier)
+
+ +

Siehe auch

+ + diff --git a/files/de/web/api/document/createattribute/index.html b/files/de/web/api/document/createattribute/index.html new file mode 100644 index 0000000000..009c6c898d --- /dev/null +++ b/files/de/web/api/document/createattribute/index.html @@ -0,0 +1,76 @@ +--- +title: Document.createAttribute() +slug: Web/API/Document/createAttribute +tags: + - API + - DOM + - Méthode + - Referenz +translation_of: Web/API/Document/createAttribute +--- +
{{ ApiRef("DOM") }}
+ +

createAttribute erstellt einen neuen Attributsknoten und gibt ihn zurück.

+ +

Syntax

+ +
attribute = document.createAttribute(name)
+
+ +

Parameter

+ + + +

Beispiel

+ +
<html>
+
+<head>
+<title> create/set/get Attribut Beispiel</title>
+
+<script type="text/javascript">
+
+function doAttrib() {
+  var node = document.getElementById("div1");
+  var a = document.createAttribute("my_attrib");
+  a.value = "newVal";
+  node.setAttributeNode(a);
+  alert(node.getAttribute("my_attrib")); // "newVal"
+}
+
+// Alternative form ohne die Verwendung von createAttribute
+//function doAttrib() {
+//  var node = document.getElementById("div1");
+//  node.setAttribute("my_attrib", "newVal");
+//  alert(node.getAttribute("my_attrib")); // "newVal"
+//}
+
+</script>
+</head>
+
+<body onload="doAttrib();">
+<div id="div1">
+<p>Some content here</p>
+</div>
+</body>
+</html>
+
+ +

Bemerkungen

+ +

Der Rückgabewert ist ein Knoten des Typs attribute. Sobald man diesen wie im vorangegangenen Beispiel hat, kann man ihren Wert festlegen, indem man der nodeValue property einen String zuweist, oder in der alternativen Form durch Benutzung der setAttribute() Methode. Der DOM beschränkt auf diese Art nicht, welche Arten von Attributen an das jeweilige Element zugewiesen werden dürfen.

+ +

Spezifikation

+ + + +

Siehe auch

+ + diff --git a/files/de/web/api/document/createdocumentfragment/index.html b/files/de/web/api/document/createdocumentfragment/index.html new file mode 100644 index 0000000000..e7ba848e49 --- /dev/null +++ b/files/de/web/api/document/createdocumentfragment/index.html @@ -0,0 +1,137 @@ +--- +title: Document.createDocumentFragment() +slug: Web/API/Document/createDocumentFragment +tags: + - API + - DOM + - Document + - DocumentFragment + - Method + - Reference +translation_of: Web/API/Document/createDocumentFragment +--- +
{{ApiRef("DOM")}}
+ +

Erzeugt ein neues {{domxref("DocumentFragment")}} Objekt.

+ +

Syntax

+ +
var fragment = document.createDocumentFragment();
+
+ +

fragment ist hierbei eine Referenz zu einem neu erstellten, leeren {{domxref("DocumentFragment")}} Objekt.

+ +

Beschreibung

+ +

DocumentFragments sind DOM Knoten (DOM Nodes). Sie sind nicht Teil des Haupt- oder Seiten-DOM-Baums. Üblicherweise werden sie verwendet, um einen Teilbaum mit Objekten und Unterobjekten zu erstellen und das Ergebnis anschließend in den Seiten-DOM-Baum einzufügen. In dem DOM-Baum wird das document fragment dann ersetzt mit allen Kindelementen.

+ +

Da das gesamte DocumentFragment nur im Speicher vorliegt ("in memory") und nicht Teil des Seiten-DOM-Baums ist, führen Veränderungen in dem DocumentFragment, wie etwa das Hinzufügen von Elementen, nicht zu einem page reflow (die Berechnung der Element Positionen und Geometrie). Dementsprechend führt die Nutzung von DocumentFragments zu einer besseren Performance.

+ +

Beispiel

+ +

Dieses Beispiel erzeugt eine Liste gängiger Browser.

+ +

HTML

+ +
<ul id="ul">
+</ul>
+ +

JavaScript

+ +
var element  = document.getElementById('ul'); // assuming ul exists
+var fragment = document.createDocumentFragment();
+var browsers = ['Firefox', 'Chrome', 'Opera',
+    'Safari', 'Internet Explorer'];
+
+browsers.forEach(function(browser) {
+    var li = document.createElement('li');
+    li.textContent = browser;
+    fragment.appendChild(li);
+});
+
+element.appendChild(fragment);
+
+ +

Resultat

+ +

{{EmbedLiveSample("Example", 600, 140)}}

+ +

Spezifikationen

+ + + + + + + + + + + + + + + + +
SpecificationStatusAnmerkungen
{{SpecName('DOM WHATWG', '#dom-document-createdocumentfragment', 'Document.createDocumentFragment()')}}{{Spec2('DOM WHATWG')}}Initiale Definition in der DOM 1 Spezifikation
+ +

Browserkompatibilität

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureFirefox (Gecko)ChromeEdgeInternet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureFirefox Mobile (Gecko)AndroidEdgeIE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

See also

+ + diff --git a/files/de/web/api/document/createelement/index.html b/files/de/web/api/document/createelement/index.html new file mode 100644 index 0000000000..8b053c1379 --- /dev/null +++ b/files/de/web/api/document/createelement/index.html @@ -0,0 +1,153 @@ +--- +title: Document.createElement() +slug: Web/API/Document/createElement +tags: + - API + - DOM + - Document + - Method + - Méthode +translation_of: Web/API/Document/createElement +--- +
{{APIRef("DOM")}}
+ + + +

In einem HTML Dokument erstellt die Document.createElement() Methode ein spezifiziertes HTML Element oder ein {{domxref("HTMLUnknownElement")}} wenn der gegebene Elementname ein unbekannter ist.

+ +

Syntax

+ +
var element = document.createElement(tagName, [optionen]);
+
+ +

Parameter

+ +
+
tagName
+
Ein String der den Typ des zu erstellenden Elements spezifiziert. Der/Die/Das {{domxref("Node.nodeName", "nodeName")}} des erstellten Elements ist mit dem Wert von tagName initialisiert. Benutze keine qualifizierten Namen (wie "html:a") mit dieser Methode.
+
optionen {{optional_inline}}
+
Ein optionales ElementCreationOptions-Objekt, welches eine einzige Eigenschaft namens is besitzt, deren Wert der Name des Tags für ein benutzerdefiniertes Element ist. Dieses benutzerdefinierte Element muss vorher mit customElements.define() definiert werden. Für mehr Informationen siehe {{anch("Web component example")}}.
+
+ +

Rückgabewert

+ +

Das neue Element.

+ +

Beispiele

+ +

Grundlegendes Beispiel

+ +

Dies erstellt ein neues <div> und fügt es vor dem Element mit der ID div1 ein.

+ +
+

HTML

+ +
<!DOCTYPE html>
+<html>
+<head>
+  <title>||Arbeiten mit Elementen||</title>
+</head>
+<body>
+  <div id="div1">Der obere Text wurde dynamisch erstellt.</div>
+</body>
+</html>
+
+ +

JavaScript

+ +
document.body.onload = addElement;
+
+function addElement () {
+  // erstelle ein neues div Element
+  // und gib ihm etwas Inhalt
+  var newDiv = document.createElement("div");
+  var newContent = document.createTextNode("Hi there and greetings!");
+  newDiv.appendChild(newContent); // füge den Textknoten zum neu erstellten div hinzu.
+
+  // füge das neu erstellte Element und seinen Inhalt ins DOM ein
+  var currentDiv = document.getElementById("div1");
+  document.body.insertBefore(newDiv, currentDiv);
+}
+
+ +

{{EmbedLiveSample("Basic_example", 500, 50)}}

+ +

Web-Komponentenbeispiel 

+ +

Das folgende Beispiel wurde aus dem Beispiel expanding-list-web-component entnommen (Siehe es live). In diesem Fall erweitert unser Custom-Element die {{domxref("HTMLUListElement")}}, welche das {{htmlelement("ul")}}  Element repräsentiert. 

+ +
// Erstelle eine Klasse für das Element
+class ExpandingList extends HTMLUListElement {
+  constructor() {
+    // Rufe immer super() in einem Konstruktor auf.
+    super();
+
+    // Konstruktordefinition wurde der kürze halber weggelassen
+    ...
+  }
+}
+
+// Definiere das neue Element
+customElements.define('expanding-list', ExpandingList, { extends: "ul" });
+ +

Würden wir eine Instanz dieses Elements programmatisch erstellen wollen, so würden wir einen Aufruf über den folgenden Ausschnitt machen: 

+ +
let expandingList = document.createElement('ul', { is : 'expanding-list' })
+ +

Dem neuen Element wird ein is Attribut hinzugefügt, dessen Wert das Custom-Element's Tag-Name ist. 

+ +
+

Notiz: Für Backwards-Kompatiblität mit früheren Versionen der Spezifikationen des Custom-Elements, erlauben einige Browser einen String, statt einem Objekt, als Parameter zu übergeben, wobei der Wert des Strings der Tag-Name des Custom-Elements ist. 

+
+ +

Notizen

+ + + +

Spezifikationen

+ + + + + + + + + + + + + + + + +
SpezifikationStatusKommentar
{{SpecName('DOM WHATWG', "#dom-document-createelement", "Document.createElement")}}{{Spec2('DOM WHATWG')}}
+ + + +

Browser-Kompatibiltät

+ +

{{Compat("api.Document.createElement")}}

+ +

Siehe auch

+ + + + diff --git a/files/de/web/api/document/createelementns/index.html b/files/de/web/api/document/createelementns/index.html new file mode 100644 index 0000000000..3f310fdb49 --- /dev/null +++ b/files/de/web/api/document/createelementns/index.html @@ -0,0 +1,175 @@ +--- +title: Document.createElementNS() +slug: Web/API/Document/createElementNS +translation_of: Web/API/Document/createElementNS +--- +
{{ApiRef("DOM")}}
+ +
Erzeugt ein Element mit der angegebenen Namespace-URL und einem Namen.
+ +
 
+ +
Um ein Element zu definieren, ohne eine Namespace-URL anzugeben, verwenden Sie die Methode createElement.
+ +

Syntax

+ +
var element = document.createElementNS(namespaceURI, qualifiedName[, options]);
+
+ +

Parameter

+ +
+
namespaceURI
+
Ein String, der die mit dem Element verknüpfte Namespace-URL angibt. Die Eigenschaft namespaceURI des neu erstellten Elements wird mit dem Wert von namespaceURI initialisiert (siehe Gültige Namespace-URLs).
+
qualifiedName
+
Ein String, der den Namen des Elements angibt. Die Eigenschaft nodeName des neu erstellten Elements wird mit dem Wert von qualifiedName initialisiert.
+
optionsOptional
+
Das optionale Objekt ElementCreationOptions enthält eine einzelne Eigenschaft mit Namen  is, dessen Wert der Tag-Name eines zuvor mit customElements.define() definierten angepassten Elements ist. Aus Gründen der Abwärtskompatibilität erlauben einige Browser hier auch die Übergabe eines Strings mit dem Taf-Namen (s. Custom Elements specification). Siehe Extending native HTML elements für weitere Informationen zur Verwendung dieses Parameters.
+
Das neue Element erhält ein Attribut mit Namen is dessen Wert den Tag-Namen des Elements enthält. Angepasste Elemente sind ein experimentelles Feature, das nich in allen Browsern verfügbar ist.
+
+ +

Rückgabewert

+ +

Das neu erstelle Element.

+ +

Gültige Namespace-URLs

+ + + +

Beispiel

+ +

Dies erstellt ein neues Element vom Typ <div> im XHTML-Namespace und fügt es dem vbox-Element hinzu. Obwohl dies kein besonders sinnvolles XUL-Document ist, demonstriert es die Verwendung von Elementen verschiedener Namespaces innerhalb eines Dokuments:

+ +
<?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("This is text that was constructed dynamically with createElementNS and createTextNode then inserted into the document using appendChild.");
+   newdiv.appendChild(txtnode);
+   container.appendChild(newdiv);
+ }
+
+]]></script>
+
+ <vbox id='ContainerBox' flex='1'>
+  <html:div>
+   The script on this page will add dynamic content below:
+  </html:div>
+ </vbox>
+
+</page>
+
+ +
+

Das obige Beispiel verwendet ein Inline-Skript, was für XHTML-Dokumente nicht empfohlen wird. Dieses Beispiel ist eigentlich ein XUL-Dokument mit eingebettetem XHTML. Nichts desto trotz bleibt die Empfehlung bestehen.

+
+ +

Spezifikationen

+ + + + + + + + + + + + + + +
SpezigikationStatusKpmmentar
{{SpecName('DOM WHATWG', "#dom-document-createelementns", "Document.createElement")}}{{Spec2('DOM WHATWG')}} 
+ +

Browser-Kompatibilität

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
options argument{{CompatVersionUnknown}}[1]{{CompatNo}}{{CompatGeckoDesktop(50)}}[2][3]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

[1] In vorangegangenen Versionen dieser Spezifikation war dieses Argument ein einfacher String, dessen Wert der Tag-Name eines angepassten Elements ist. Aus Gründen der Abwärtskompatibilität akzeptiert Chrome hier beide Formate

+ +

[2] Siehe [1] oben: Wie Chrome, akzeptiert hier auch Firefox einen String anstelle eines Objekts. Allerdings erst ab Version 51 aufwärts. In Version 50 muss  options ein Objekt sein.

+ +

[3] Um in Firefox mit angepassten Elementen zu experimentieren müssen die Einstellungen  dom.webcomponents.enabled und dom.webcomponents.customelements.enabled auf true gesetzt werden.

+ +

Siehe auch

+ + diff --git a/files/de/web/api/document/createtextnode/index.html b/files/de/web/api/document/createtextnode/index.html new file mode 100644 index 0000000000..53fae2cc1c --- /dev/null +++ b/files/de/web/api/document/createtextnode/index.html @@ -0,0 +1,131 @@ +--- +title: Document.createTextNode() +slug: Web/API/Document/createTextNode +tags: + - API + - DOM + - Méthode + - Referenz + - Textknoten + - Textnode +translation_of: Web/API/Document/createTextNode +--- +
{{APIRef("DOM")}}
+ +

Erzeugt einen Textknoten.

+ +

Syntax

+ +
var text = document.createTextNode(data);
+
+ + + +

Example

+ +
<!DOCTYPE html>
+<html lang="en">
+<head>
+<title>createTextNode example</title>
+<script>
+function addTextNode(text) {
+  var newtext = document.createTextNode(text),
+      p1 = document.getElementById("p1");
+
+  p1.appendChild(newtext);
+}
+</script>
+</head>
+
+<body>
+  <button onclick="addTextNode('JA! ');">JA!</button>
+  <button onclick="addTextNode('NEIN! ');">NEIN!</button>
+  <button onclick="addTextNode('WIR SCHAFFEN DAS! ');">WIR SCHAFFEN DAS!</button>
+
+  <hr />
+
+  <p id="p1">Erste Zeile des Absatzes.</p>
+</body>
+</html>
+
+ +

Spezifikationen

+ + + + + + + + + + + + + + + + + + + + + +
SpecifikationStatusKommentar
{{SpecName("DOM3 Core", "core.html#ID-1975348127", "Document.createTextNode()")}}{{Spec2("DOM3 Core")}}Keine Änderung
{{SpecName("DOM2 Core", "core.html#ID-1975348127", "Document.createTextNode()")}}{{Spec2("DOM2 Core")}}Ursprüngliche Definition
+ +

Browser Kompatibilität

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Grundlegende Unterstützung{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Grundlegende Unterstützung{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
diff --git a/files/de/web/api/document/createtreewalker/index.html b/files/de/web/api/document/createtreewalker/index.html new file mode 100644 index 0000000000..61e526b92c --- /dev/null +++ b/files/de/web/api/document/createtreewalker/index.html @@ -0,0 +1,241 @@ +--- +title: Document.createTreeWalker() +slug: Web/API/Document/createTreeWalker +tags: + - API + - DOM + - DOM-Referenz + - Document + - Dokument + - Méthode +translation_of: Web/API/Document/createTreeWalker +--- +
{{ApiRef("Document")}}
+ +

Die Methode Document.createTreeWalker() erzeugt ein neues {{domxref("TreeWalker")}} Objekt und gibt dieses zurück.

+ +

Syntax

+ +
treeWalker = document.createTreeWalker(wurzel, anzeigeFilter, filter, entityReferenceExpansion);
+
+ +

Parameter

+ +
+
wurzel
+
Ist der Ursprungs- oder Wurzelknoten {{domxref("Node")}} des {{domxref("TreeWalker")}}-Durchlaufens. Normalerweise ist dies ein Element, das zum Dokument gehört.
+ +
anzeigeFilter {{optional_inline}}
+
Optionale unsigned longBitmaske, erstellt durch bitweise ODER-Verknüpfung der Konstanten von NodeFilter. Erlaubt eine bequeme Filterung auf bestimmte Knotentypen. Der Standardwert ist 0xFFFFFFFF, auch repräsentiert durch die SHOW_ALL-Konstante. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Konstantenumerischer WertBeschreibung
NodeFilter.SHOW_ALL-1 (Maximalwert von unsigned long)Zeigt alle Knoten.
NodeFilter.SHOW_ATTRIBUTE {{deprecated_inline}}2Zeigt Attribut-Knoten {{domxref("Attr")}}. Das ist nur sinnvoll, wenn der {{domxref("TreeWalker")}} mit einem {{domxref("Attr")}}-Knoten als Wurzel erzeugt wird. In diesem Fall erscheint der Attribut-Knoten an der ersten Position bei der Durchquerung. Da Attribute nie Kind-Knoten anderer Knoten sind, erscheinen sie nicht, wenn der Dokumentenbaum durchlaufen wird.
NodeFilter.SHOW_CDATA_SECTION {{deprecated_inline}}8Zeigt {{domxref("CDATASection")}}-Knoten.
NodeFilter.SHOW_COMMENT128Zeigt {{domxref("Comment")}}-Knoten.
NodeFilter.SHOW_DOCUMENT256Zeigt {{domxref("Document")}}-Knoten.
NodeFilter.SHOW_DOCUMENT_FRAGMENT1024Zeigt {{domxref("DocumentFragment")}}-Knoten.
NodeFilter.SHOW_DOCUMENT_TYPE512Zeigt {{domxref("DocumentType")}}-Knoten.
NodeFilter.SHOW_ELEMENT1Zeigt {{domxref("Element")}}-Knoten.
NodeFilter.SHOW_ENTITY {{deprecated_inline}}32Zeigt {{domxref("Entity")}}-Knoten. Dies ist nur sinnvoll, wenn ein {{domxref("TreeWalker")}} mit einem {{domxref("Entity")}}-Knoten als Wurzel erzeugt wird. In diesem Fall erscheint der {{domxref("Entity")}}-Knoten an der ersten Position bei der Durchquerung. Da Entity-Knoten nie Kind-Knoten anderer Knoten sind, erscheinen sie nicht, wenn der Dokumentenbaum durchlaufen wird.
NodeFilter.SHOW_ENTITY_REFERENCE {{deprecated_inline}}16Shows {{domxref("EntityReference")}} nodes.
NodeFilter.SHOW_NOTATION {{deprecated_inline}}2048Zeigt {{domxref("Notation")}}-Knoten. Dies ist nur sinnvoll, wenn ein {{domxref("TreeWalker")}} mit einem {{domxref("Notation")}}-Knoten als Wurzel erzeugt wird. In diesem Fall erscheint der {{domxref("Notation")}}-Knoten an der ersten Position bei der Durchquerung. Da Entity-Knoten nie Kind-Knoten anderer Knoten sind, erscheinen sie nicht, wenn der Dokumentenbaum durchlaufen wird.
NodeFilter.SHOW_PROCESSING_INSTRUCTION64Zeigt {{domxref("ProcessingInstruction")}}-Knoten.
NodeFilter.SHOW_TEXT4Zeigt {{domxref("Text")}}-Knoten.
+
+ +
filter {{optional_inline}}
+
Ein optionaler {{domxref("NodeFilter")}}. Muss ein ein Objekt mit einer Methode namens acceptNode sein, die vom {{domxref("TreeWalker")}} aufgerufen wird. Diese Methode entscheidet, ob ein übergebener Knoten, der schon von anzeigeFilter durchgelassen wurde, ausgegeben wird oder nicht.
+ +
entityReferenceExpansion {{optional_inline}} {{obsolete_inline}}
+
Optionaler {{domxref("Boolean")}}-Schalter. Entscheidet, ob der Teilbaum unter einer {{domxref("EntityReference")}} ausgelassen werden soll, wenn das Element ausgelassen wird.
+
+ +

Beispiel

+ +

Das folgende Beispiel läuft über alle Knoten im body, filtert die Menge auf Elementknoten und gibt im filter jeden Knoten als durchlässig an (die Filterung auf die Elementknoten hätte auch in der acceptNode()-Methode erfolgen können). +Mithilfe des treeWalker werden alle durchgelassenen Knoten in ein Array gesammelt.

+ +
var treeWalker = document.createTreeWalker(
+  document.body,
+  NodeFilter.SHOW_ELEMENT,
+  { acceptNode: function(node) { return NodeFilter.FILTER_ACCEPT; } },
+  false
+);
+
+var nodeList = [];
+
+while(treeWalker.nextNode()) nodeList.push(treeWalker.currentNode);
+
+ +

Spezfikationen

+ + + + + + + + + + + + + + + + + + + +
SpezfikationStatusBemerkung
{{SpecName('DOM WHATWG', '#dom-document-createtreewalker', 'Document.createTreeWalker')}}{{Spec2('DOM WHATWG')}}expandEntityReferences-Parameter wurde entfernt. whatToShow- und filter-Parameter wurden als optional markiert.
{{SpecName('DOM2 Traversal_Range', 'traversal.html#NodeIteratorFactory-createTreeWalker', 'Document.createTreeWalker')}}{{Spec2('DOM2 Traversal_Range')}}Initiale Definition
+ +

Browser-Kompatibilität

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
grundsätzliche Unterstützung1.0{{CompatGeckoDesktop("1.8.1")}}9.09.03.0
whatToShow und filter optional1.0{{CompatGeckoDesktop("12")}}{{CompatNo}}{{CompatVersionUnknown}}3.0
expandEntityReferences1.0{{CompatGeckoDesktop("1.8.1")}}
+ In {{CompatGeckoDesktop("12")}} entfernt.
9.09.03.0
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
grundsätzliche Unterstützung{{CompatVersionUnknown}}{{CompatGeckoMobile("1.8.1")}}{{CompatVersionUnknown}}9.03.0
whatToShow und filter optional{{CompatVersionUnknown}}{{CompatGeckoDesktop("12")}}{{CompatNo}}{{CompatVersionUnknown}}3.0
expandEntityReferences{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.8.1")}}
+ In {{CompatGeckoDesktop("12")}} entfernt
{{CompatVersionUnknown}}9.03.0
+
+ +

Siehe auch

+ + diff --git a/files/de/web/api/document/dir/index.html b/files/de/web/api/document/dir/index.html new file mode 100644 index 0000000000..532837e9dd --- /dev/null +++ b/files/de/web/api/document/dir/index.html @@ -0,0 +1,95 @@ +--- +title: Document.dir +slug: Web/API/Document/dir +translation_of: Web/API/Document/dir +--- +

{{ApiRef("")}}

+ +

Die Document.dir Eigenschaft ist ein {{domxref("DOMString")}}, welcher die direktionaler Bedeutung von einem Text eines Dokuments repräsentiert. Entweder von links nach rechts (Standard) oder rechts nach links. Mögliche Werte sind 'rtl' rechts nach links, und 'ltr', links nach rechts.

+ +

Syntax

+ +
dirStr = document.dir;
+document.dir = dirStr;
+
+ +

Spezifikationen

+ + + + + + + + + + + + + + + + +
SpezifikationenStatusKommentar
{{SpecName("HTML WHATWG", "dom.html#the-dir-attribute:dom-dir", "Document.dir")}}{{Spec2("HTML WHATWG")}}Initiale Spezifikation
+ +

Browserkompatibilität

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basis Unterstützung{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}} [1]{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basis Unterstützung{{ CompatUnknown() }}{{CompatVersionUnknown}}{{CompatVersionUnknown}} [1]{{ CompatVersionUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +

[1] Vor Firefox 23, hat die Document.dir Eigenschaft "ltr" wiedergegeben. unabhängig der Einstellung von dem dir-Attribut im Haupt-Element (root) {{htmlelement("html")}}. Und wenn eine Richtung im <html> gesetzt war, hatte die Veränderung der Sichtbarkeit keinen Effekt (obwohl der spätere Abruf des Document.dir wird behaupten, dass die Direktionalität geändert wurde). Wenn ein solches Attribut nicht im <html> gesetzt ist und die Eigenschaft geändert wurde, werden beide sichtbaren direktionale geändert und die document.dir  Eigenschaft wird die Änderung korrekt wiedergeben.

+ +

Siehe auch

+ + diff --git a/files/de/web/api/document/document/index.html b/files/de/web/api/document/document/index.html new file mode 100644 index 0000000000..ce3bddf174 --- /dev/null +++ b/files/de/web/api/document/document/index.html @@ -0,0 +1,45 @@ +--- +title: Document() +slug: Web/API/Document/Document +tags: + - API + - DOM + - Document + - Dokument + - Méthode + - Reference +translation_of: Web/API/Document/Document +--- +
{{APIRef}}
+ +

Die Document Methode erstellt ein neues {{domxref("Document")}} Objekt das als Webseite im Browser geladen werden kann und bietet Möglichkeiten auf diese Inhalte zuzugreifen.

+ +

Konstruktor

+ +
new Document();
+
+ +

Spezifikationen

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG','#dom-document-document','Document')}}{{Spec2('DOM WHATWG')}}Initial definition.
+ +

Browser-Kompatibilität

+ + + +
{{Compat("api.Document.Document")}}
diff --git a/files/de/web/api/document/documentelement/index.html b/files/de/web/api/document/documentelement/index.html new file mode 100644 index 0000000000..aac46ae3ea --- /dev/null +++ b/files/de/web/api/document/documentelement/index.html @@ -0,0 +1,42 @@ +--- +title: document.documentElement +slug: Web/API/Document/documentElement +translation_of: Web/API/Document/documentElement +--- +

{{ApiRef}}

+ +

Zusammenfassung

+ +

Lesbar, nicht schreibbar

+ +

Gibt das Element zurück, das die Wurzel des document ist (zum Beispiel, das <html> Element für HTML Dokumente).

+ +

Syntax

+ +
var element = document.documentElement;
+
+ +

Beispiel

+ +
var rootElement = document.documentElement;
+var firstTier = rootElement.childNodes;
+
+// firstTier ist die NodeList von direkten Kindern des Wurzel-Elementes
+for (var i = 0; i < firstTier.length; i++) {
+   // hier irgendwas mit den direkten Kindern des Wurzel-Elementes mit Hilfe
+   // von firstTier[i] erledigen
+}
+ +

Beobachtungen

+ +

Dieses Objekt ist lesbar aber nicht schreibbar. Es ist praktisch um auf die Wurzel eines beliebigen Dokumentes zuzugreifen.

+ +

HTML Dokumente enthalten typischerweise ein einziges Tochter-Element, <html>, manchmal mit einem DOCTYPE. XML-Doumente enthalten oft mehrere Tochter-Elemente, einen DOCTYPE und Verarbeitungshinweise.

+ +

Deswegen sollte document.documentElement statt {{Domxref("document.firstElementChild")}} benutzt werden, um auf das Wurzel-Element zuzugreifen.

+ +

Spezifikation

+ + diff --git a/files/de/web/api/document/fullscreenchange_event/index.html b/files/de/web/api/document/fullscreenchange_event/index.html new file mode 100644 index 0000000000..7c8026858c --- /dev/null +++ b/files/de/web/api/document/fullscreenchange_event/index.html @@ -0,0 +1,87 @@ +--- +title: fullscreenchange +slug: Web/API/Document/fullscreenchange_event +translation_of: Web/API/Document/fullscreenchange_event +--- +

Das onfullscreenchange Event wird gesendet, wenn der Browser den Vollbildmodus startet oder beendet.

+ +

Allgemeine Information

+ +
+
Speifikation
+
Fullscreen
+
Schnittstelle
+
Event
+
Blubbert
+
Ja
+
Abbrechbar
+
Nein
+
Ziel
+
Dokument
+
Standardaktion
+
Keine
+
+ +

Eigenschaften

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
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}}{{jsxref("Boolean")}}Whether the event normally bubbles or not.
cancelable {{readonlyInline}}{{jsxref("Boolean")}}Whether the event is cancellable or not.
+ +

Beispiel

+ +
// Diese API hat noch immer Vendor Prefixe in den Browsern, die sie implementieren
+document.addEventListener("fullscreenchange", function( event ) {
+
+    // Das Event selber hat keine Informationen über darüber, ob sich der Browser
+    // im Vollbildmodus befindet, aber man kann diesen über die Fullscreen API
+    // erhalten
+    if ( document.fullscreen ) {
+
+        // Das Ziel des Events ist immer das Dokument,
+        // aber man kann das eigentliche Element im Vollbildmodus über die API
+        // abrufen
+        document.fullscreenElement;
+    }
+
+});
+ +

Verwandte Events

+ + + +

Siehe auch

+ + diff --git a/files/de/web/api/document/getelementbyid/index.html b/files/de/web/api/document/getelementbyid/index.html new file mode 100644 index 0000000000..dfb6cc0d36 --- /dev/null +++ b/files/de/web/api/document/getelementbyid/index.html @@ -0,0 +1,131 @@ +--- +title: Document.getElementById() +slug: Web/API/Document/getElementById +tags: + - API + - DOM + - Méthode + - Referenz +translation_of: Web/API/Document/getElementById +--- +
{{ ApiRef("DOM") }}
+ +
 
+ +
Gibt eine Referenz zu einem Element anhand seiner ID zurück.
+ +
 
+ +

Syntax

+ +
element = document.getElementById(id);
+
+ +

Parameter

+ + + +

Beispiel

+ +
<!DOCTYPE html>
+<html>
+<head>
+  <title>getElementById Beispiel</title>
+  <script>
+  function changeColor(newColor) {
+    var elem = document.getElementById("para1");
+    elem.style.color = newColor;
+  }
+  </script>
+</head>
+<body>
+  <p id="para1">Irgendein Text</p>
+  <button onclick="changeColor('blue');">Blau</button>
+  <button onclick="changeColor('red');">Rot</button>
+</body>
+</html>
+
+ +

Anmerkungen

+ +

Neue Benutzer sollten beachten, dass die Groß- und Kleinschreibung bei "Id" im Namen der Methode korrekt sein muss, damit der Code funktioniert - 'getElementByID' funktioniert nicht, auch wenn es richtig zu sein scheint.

+ +

Wenn kein Element mit der angegebenen id existiert, gibt die Funktion null zurück. Beachte, dass der ID-Parameter auf Groß- und Kleinschreibung achtet. Daraus folgt, dass document.getElementById("Main") anstatt des Elements <div id="main"> null zurückgibt, weil "M" und "m" für den Zweck der Methode unterschiedlich sind.

+ +

Elemente die sich nicht im Dokument befinden werden nicht von getElementById gesucht. Wenn man ein Element erstellt und ihm eine ID zuweist, so muss man das Element mit insertBefore oder einer ähnlichen Methode in den Dokumentenbaum einfügen, bevor man darauf mit getElementById zugreifen kann.

+ +
var element = document.createElement("div");
+element.id = 'testqq';
+var el = document.getElementById('testqq'); // el wird null!
+
+ +

Nicht-HTML-Dokumente. Die DOM-Implementierung muss eine Information enthalten, welche angibt, welches Attribut vom Typ ID ist. Attribute mit dem Namen "id" sind solange nicht vom Typ ID bis sie in der Dokumenttypdefinition als solche definiert werden. Das id-Attribut ist in gebräuchlichen Fällen wie bei XHTML, XUL und anderen als ID-Typ definiert. Implementierungen, die nicht wissen, ob ein Attribut vom Typ ID ist oder nicht geben erwartungsgemäß null zurück.

+ +

Browserkompatibilität

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support1.0{{ CompatGeckoDesktop(1.0) }}5.57.01.0
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support1.0{{ CompatGeckoMobile(1.0) }}6.06.01.0
+
+ +

Spezifikation

+ +

getElementById wurde in DOM Level 1 für HTML Dokumente eingeführt und in DOM Level 2 zu allen Dokumenten verschoben. 

+ + + +

Siehe auch

+ + diff --git a/files/de/web/api/document/getelementsbyclassname/index.html b/files/de/web/api/document/getelementsbyclassname/index.html new file mode 100644 index 0000000000..182fef2f42 --- /dev/null +++ b/files/de/web/api/document/getelementsbyclassname/index.html @@ -0,0 +1,105 @@ +--- +title: Document.getElementsByClassName() +slug: Web/API/Document/getElementsByClassName +tags: + - API + - DOM + - DOM Element Methoden + - Gecko + - Gecko DOM Referenz + - HTML5 + - Méthode + - Referenz +translation_of: Web/API/Document/getElementsByClassName +--- +

{{APIRef("DOM")}}

+ +

Gibt ein Array-ähnliches Objekt von allen Kindelementen welche den gegebenen Klassennamen besitzen. Wenn dies auf das document-Objekt ausgeführt wird, wird das gesamte Dokument durchsucht, inklusive des root-Knoten. Man kann ebenfalls {{domxref("Element.getElementsByClassName", "getElementsByClassName()")}} mit jedem Element aufrufen; es werden nur Nachfolgende Elemente des gegebenenen root-Element zurückgegeben.

+ +

Syntax

+ +
var elements = document.getElementsByClassName(names); // oder:
+var elements = rootElement.getElementsByClassName(names);
+ + + +

Beispiele

+ +

Alle Elemente der Klasse 'test' holen:

+ +
document.getElementsByClassName('test');
+ +

Alle Elemente die sowohl die Klassen 'red' und 'test' verwenden selektieren:

+ +
document.getElementsByClassName('red test');
+ +

Alle Elemente der Klasse 'test' die innerhalb eines Elements mit der ID 'main' selektieren:

+ +
document.getElementById('main').getElementsByClassName('test');
+ +

Man kann auch Methoden von Array.prototype auf {{ domxref("HTMLCollection") }} anwenden, in dem die HTMLCollection  in dem sie an die this Werte der Methoden übergeben wird. Hier finden wir alle div-Elemente der Klasse 'test':

+ +
var testElements = document.getElementsByClassName('test');
+var testDivs = Array.prototype.filter.call(testElements, function(testElement){
+    return testElement.nodeName === 'DIV';
+});
+ +

Browserkompabilität

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{ CompatVersionUnknown() }}3.09.0{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +

Spezifikation

+ + diff --git a/files/de/web/api/document/head/index.html b/files/de/web/api/document/head/index.html new file mode 100644 index 0000000000..63b389112d --- /dev/null +++ b/files/de/web/api/document/head/index.html @@ -0,0 +1,73 @@ +--- +title: Document.head +slug: Web/API/Document/head +tags: + - Referenz +translation_of: Web/API/Document/head +--- +

{{APIRef("DOM")}}

+ +

Gibt das {{HTMLElement("head")}} Element des aktuellen Dokuments aus. Ist mehr als ein <head>  Element vorhanden, wird das erste Element ausgegeben.

+ +

Syntax

+ +
var objRef = document.head;
+
+ +

Beispiel

+ +
// in HTML: <head id="my-document-head">
+var aHead = document.head;
+
+alert(aHead.id); // "my-document-head";
+
+alert( document.head === document.querySelector("head") ); // true
+
+ +

Anmerkungen

+ +

document.head ist nur lesbar. Der Versuch dieser Eigenschaft einen Wert zu zuweisen, wird ohne Ausgabe einer Fehlermeldung fehlschlagen, oder, bei verwendetem
+ ECMAScript Strict Mode in einem Gecko Browser, mit einem TypeError quittiert.

+ +

Spezifikation

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpezifikationStatusKommentar
{{SpecName('HTML WHATWG','dom.html#dom-document-head','Document.head')}}{{Spec2('HTML WHATWG')}}Initiale Definition.
{{SpecName('HTML5.1','dom.html#dom-document-head','Document.head')}}{{Spec2('HTML5.1')}} 
{{SpecName('HTML5 W3C','dom.html#dom-document-head','Document.head')}}{{Spec2('HTML5 W3C')}} 
+ +

Browser Kompatibilität

+ +

 

+ + + +

{{Compat("api.Document.head")}}

+ +

 

+ +

Siehe auch

+ + diff --git a/files/de/web/api/document/importnode/index.html b/files/de/web/api/document/importnode/index.html new file mode 100644 index 0000000000..8420b6f794 --- /dev/null +++ b/files/de/web/api/document/importnode/index.html @@ -0,0 +1,93 @@ +--- +title: Document.importNode() +slug: Web/API/Document/importNode +tags: + - API + - DOM + - Dokument + - Knoten + - Kopie + - Méthode + - Referenz + - importNode +translation_of: Web/API/Document/importNode +--- +
{{APIRef("DOM")}}
+ +

Die {{domxref("Document")}}-Methode importNode() erzeugt eine neue Kopie eines konkreten Knotens ({{domxref("Node")}}) oder Dokumenten-Fragments ({{domxref("DocumentFragment")}}) eines anderen Dokuments, so dass diese dann in das aktuelle Dokument eingefügt werden kann.  An dieser Stelle ist es noch nicht im Dokumentenbaum eingefügt, um das zu erreichen, muss eine Methode wie {{domxref("Node.appendChild", "appendChild()")}} oder {{domxref("Node.insertBefore", "insertBefore()")}} aufgerufen werden.

+ +

Syntax

+ +
var knoten = document.importNode(externerKnoten, deep);
+
+ +
+
externerKnoten
+
Der neue Knoten oder das neue Dokumenten-Fragment, welches in das aktuelle Dokument importiert werden soll. Nach dem Import ist der Elternknoten null, da der neue Knoten noch nicht in den Dokumentenbaum eingefügt wurde.
+
deep
+
Ein boolscher Wert der anzeigt, ob der komplette Unterbaum vonexternalNode importiert werden soll. Ist dieser Parameter true, werden externalNode so wie all seine Nachfahren kopiert; Ist er false, wird nur der einzelne Knoten, externalNode, importiert.
+
+ +
+

In der DOM4-Spezifikation, ist deep als optionales Argument angeführt. Wird es weggelassen, verhält sich die Methode als ob der Wert von deeptrue wäre, was zu standardmäßigen tiefen Kopieren führt. Um flach zu kopieren, muss deep explizit auf false gesetzt werden.

+ +

Dieses Verhalten wurde in der letzten Spezifikation geändert, der Wert von deep wird bei Weglassen auf false gesetzt. Obwohl es immer noch optional ist, empfehlen wir für Vorwärts- und Rückwärtskompatibilität das deep-Argument immer explizit anzugeben. Seit Gecko 28.0 {{geckoRelease(28)}} ist eine Konsolenwarnung implementiert, wenn das Argument weggelassen wird. Seit Gecko 29.0 {{geckoRelease(29)}}) ist flaches Kopieren das Standardverhalten.

+
+ +

Beispiel

+ +
var iframe = document.getElementsByTagName("iframe")[0];
+var oldNode = iframe.contentWindow.document.getElementById("myNode");
+var newNode = document.importNode(oldNode, true);
+document.getElementById("container").appendChild(newNode);
+
+ +

Anmerkungen

+ +

Der Originalknoten wird nicht aus dem Ursprungsdokument entfernt. Der importierte Knoten ist des Weiteren eine Kopie des ursprünglichen.

+ +

 

+ +

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.

+ +

 

+ +

Spezifikationen

+ + + + + + + + + + + + + + + + + + + +
SpezifikationenStatusKommentar
{{SpecName("DOM WHATWG", "#dom-document-importnode", "document.importNode()")}}{{Spec2("DOM WHATWG")}} 
{{SpecName("DOM2 Core", "core.html#Core-Document-importNode", "document.importNode()")}}{{Spec2("DOM2 Core")}}Ursprüngliche Definition
+ +

Browserkompatibilität

+ +
+ + +

{{Compat("api.Document.importNode")}}

+
+ +

Siehe auch

+ + diff --git a/files/de/web/api/document/index.html b/files/de/web/api/document/index.html new file mode 100644 index 0000000000..f9b00cacfc --- /dev/null +++ b/files/de/web/api/document/index.html @@ -0,0 +1,405 @@ +--- +title: Document +slug: Web/API/Document +tags: + - DOM + - Gecko + - Gecko DOM Referenz +translation_of: Web/API/Document +--- +
{{ ApiRef("DOM") }}
+ +
+ +

Zusammenfassung

+ +

Jede im Browswer geladene Webseite hat ihr eigenen document Objekt.  Das Document Interface dient als Einstiegspunkt in den Inhalt der Webseite (der DOM tree, beinhaltet Elemente wie {{HTMLElement("body")}} und {{HTMLElement("table")}}) und unterstützt Funktionen, die global für das Dokument gelten(z.B. das Aufrufen der URL der Seite und das Erstellen neuer Elemente im Dokument).

+ +

Ein Dokument-Objekt kann von verschiedenen APIs bezogen werden:

+ + + +

Depending on the kind of the document (e.g. HTML or XML), different APIs may be available on the document object.

+ + + +

In der Zukunft, alle diese Interfaces werden zusammengefasst zum Document Interface.

+ +

Eigenschaften

+ +
+

Hinweis: Das Document Interface erbt auch vom {{domxref("Node")}} und {{domxref("EventTarget")}} Interface.

+
+ +
+
{{domxref("Document.all")}} {{Deprecated_inline}} {{non-standard_inline}}
+
Provides access to all elements with an id. This is a legacy non-standard interface, you should use the {{domxref("Document.getElementById()")}} method instead.
+
{{domxref("Document.async")}} {{Deprecated_inline}}
+
Used with {{domxref("document.load")}} to indicate an asynchronous request.
+
{{domxref("Document.characterSet")}} {{experimental_inline}}
+
Returns the character set being used by the document.
+
{{domxref("Document.compatMode")}} {{experimental_inline}}
+
Indicates whether the document is rendered in Quirks or Strict mode.
+
{{domxref("Document.contentType")}} {{experimental_inline}}
+
Returns the Content-Type from the MIME Header of the current document.
+
{{domxref("Document.doctype")}}
+
Returns the Document Type Definition (DTD) of the current document.
+
{{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")}}

+ +

Erweiterung für HTML Dokumente

+ +

Das Document Interface für HTML Dokumente erbt vom {{domxref("HTMLDocument")}} Interface oder, ist seit HTML5 erweitert für solche Dokumente:

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

Methoden

+ +
+

Hinweis: Das Document Interface erbt auch vom {{domxref("Node")}} und {{domxref("EventTarget")}} Interface.

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

Erweiterung für HTML Dokumente

+ +

Das Document Interface für HTML Dokumente erbt vom {{domxref("HTMLDocument")}} Interface oder ist seit HTML5 erweitert für solche Dokumente:

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

Spezifikationen

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpezifikationStatusKommentar
{{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 Kompatibilität

+ +

Firefox Hinweise

+ +

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 Hinweise

+ +

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/de/web/api/document/queryselector/index.html b/files/de/web/api/document/queryselector/index.html new file mode 100644 index 0000000000..7fadcd87ce --- /dev/null +++ b/files/de/web/api/document/queryselector/index.html @@ -0,0 +1,129 @@ +--- +title: Document.querySelector() +slug: Web/API/Document/querySelector +tags: + - API + - DOM + - Funktion + - Methode(2) + - Méthode + - Referenz + - Selektor + - Selektoren +translation_of: Web/API/Document/querySelector +--- +
{{ApiRef("DOM")}}
+ +

Die Methode querySelector() von {{domxref("Document")}} gibt das erste {{domxref("Element")}} innerhalb eines Dokuments zurück, welches dem angegebenen Selektor bzw. Selektoren entspricht. Wurden keine Übereinstimmungen gefunden wird null zurückgegeben.

+ +
+

Hinweis: Der Abgleich erfolgt indem sämtliche Knoten des Dokuments und deren Unterknoten der Reihe nach mittels Tiefensuche in Hauptreihenfolge (depth-first pre-order) durchlaufen werden.

+
+ +

Syntax

+ +
element = document.querySelector(selectors);
+
+ +

Parameter

+ +
+
selectors
+
Ein {{domxref("DOMString")}} mit einem oder mehreren Selektoren die abgeblichen werden sollen. Dieser String muss ein gültiger CSS-Selektor-String sein. Ist dies nicht der Fall, wird eine SYNTAX_ERR Exception ausgelöst. Weitere Informationen zu Selektoren und deren Verwaltung finden Sie unter DOM Elemente mittels Selektoren ermitteln.
+
+ +
+

Hinweis: Zeichen, die nicht zur Standard-CSS-Syntax gehören, müssen mit einem Backslash-Zeichen maskiert werden. Da JavaScript auch Backslash-Escape-Anweisungen verwendet, müssen Sie beim Schreiben von String-Literalen mit diesen Zeichen besonders vorsichtig sein. Weitere Informationen finden Sie unter {{anch("Sonderzeichen maskieren")}}.

+
+ +

Rückgabewert

+ +

Ein {{domxref("Element")}}-Objekt, das das erste Element des Dokuments darstellt, das der angegebenen Gruppe von CSS-Selektoren entspricht, oder null, wenn keine Übereinstimmungen vorhanden sind.

+ +

Wenn Sie eine Liste aller Elemente benötigen, die mit den angegebenen Selektoren übereinstimmen, verwenden Sie stattdessen {{domxref("document.querySelectorAll()", "querySelectorAll()")}}.

+ +

Exceptions

+ +
+
SYNTAX_ERR
+
Die Syntax der angegebenen Selektoren ist ungültig.
+
+ +

Nutzungshinweise

+ +

Wenn der angegebene Selektor mit einer ID übereinstimmt, die im Dokument fälschlicherweise mehrmals vorkommt, wird das erste Element mit dieser ID zurückgegeben.

+ +

CSS-Pseudoelemente geben niemals Elemente zurück, wie in der Selektoren-API angegeben.

+ +

Sonderzeichen maskieren

+ +

Um mit einer ID oder Selektoren abzugleichen, die nicht der Standard-CSS-Syntax entsprechen (z. B. durch einen unzulässigen Doppelpunkt oder Leerzeichen), müssen Sie das Zeichen mit einem Backslash ("\") maskieren. Da der Backslash selbst ebenfalls ein Maskierungszeichen in JavaScript ist, müssen Sie ihn bei der Eingabe eines Stringliterals zweimal maskieren (einmal für den JavaScript String und einmal für querySelector()):

+ +
<div id="foo\bar"></div>
+<div id="foo:bar"></div>
+
+<script>
+  console.log('#foo\bar');               // "#fooar" (\b is the backspace control character)
+  document.querySelector('#foo\bar');    // Does not match anything
+
+  console.log('#foo\\bar');              // "#foo\bar"
+  console.log('#foo\\\\bar');            // "#foo\\bar"
+  document.querySelector('#foo\\bar'); // Match the first div
+
+  document.querySelector('#foo:bar');    // Does not match anything
+  document.querySelector('#foo\\:bar');  // Match the second div
+</script>
+ +

Beispiele

+ +

Erstes Element ermitteln, das mit einer Klasse übereinstimmt

+ +

In diesem Beispiel wird das erste Element im Dokument mit der Klasse "myclass" zurückgegeben:

+ +
var el = document.querySelector(".myclass");
+
+ +

Ein komplexerer Selektor

+ +

Selektoren können auch sehr mächtig sein, wie das folgende Beispiel zeigt. Hier wird das erste {{HTMLElement("input")}}-Element mit dem Namen "login" (<input name="login"/>) innerhalb eines {{HTMLElement("div")}}, dessen Klasse "user-panel main" ist (<div class="user-panel main">), im Dokument zurückgegeben:

+ +
var el = document.querySelector("div.user-panel.main input[name='login']");
+
+ +

Spezifikationen

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("Selectors API Level 2", "#interface-definitions", "document.querySelector()")}}{{Spec2("Selectors API Level 2")}} 
{{SpecName("Selectors API Level 1", "#interface-definitions", "document.querySelector()")}}{{Spec2("Selectors API Level 1")}}Initiale Definition
+ +

Browserkompatibilität

+ + + +
{{Compat("api.Document.querySelector")}}
+ +

Siehe auch

+ + diff --git a/files/de/web/api/document/queryselectorall/index.html b/files/de/web/api/document/queryselectorall/index.html new file mode 100644 index 0000000000..80ab2a83c2 --- /dev/null +++ b/files/de/web/api/document/queryselectorall/index.html @@ -0,0 +1,172 @@ +--- +title: Document.querySelectorAll() +slug: Web/API/Document/querySelectorAll +tags: + - API + - Document + - querySelectorAll +translation_of: Web/API/Document/querySelectorAll +--- +
{{APIRef("DOM")}}
+ +

Die Methode querySelectorAll() von {{domxref("Document")}} gibt eine statische (nicht live) {{domxref("NodeList")}} zurück, die eine Liste der Elemente des Dokuments darstellt, die mit der angegebenen Selektorgruppe übereinstimmen.

+ +
+

Hinweis: Diese Methode wird basierend auf dem Mixin der Methode {{domxref("ParentNode.querySelectorAll", "querySelectorAll()")}} von {{domxref("ParentNode")}} implementiert.

+
+ +

Syntax

+ +
elementList = parentNode.querySelectorAll(selectors);
+
+ +

Parameter

+ +
+
selectors
+
Ein {{domxref("DOMString")}} der einen oder mehrere Selektoren zum Abgleich enthält. Dieser String muss ein valider CSS-Selektor-String sein, andernfalls wird eine SyntaxError Exception ausgelöst. Weitere Informationen zu Selektoren und deren Verwaltung finden Sie unter DOM Elemente mittels Selektoren ermitteln. Es können mehrere durch Kommata getrennte Selektoren angegeben werden.
+
+ +
+

Hinweis: Zeichen, die nicht zur Standard-CSS-Syntax gehören, müssen mit einem Backslash-Zeichen maskiert werden. Da JavaScript auch Backslash-Escape-Anweisungen verwendet, müssen Sie beim Schreiben von String-Literalen mit diesen Zeichen besonders vorsichtig sein. Weitere Informationen finden Sie unter {{anch("Sonderzeichen maskieren")}}.

+
+ +

Rückgabewert

+ +

Eine statische (nicht-live) {{domxref("NodeList")}} mit je einem {{domxref("Element")}}-Objekt für jedes Element das mind. einem der angegebenen Selektoren entspricht oder eine leere {{domxref("NodeList")}} im Falle keiner Übereinstimmungen.

+ +
+

Hinweis: Wenn selectors ein CSS Pseudo-Element enthält ist die zurückgegebene Liste immer leer.

+
+ +

Exceptions

+ +
+
SyntaxError
+
Die Syntax des selectors-String ist ungültig.
+
+ +

Beispiele

+ +

Eine Liste von Übereinstimmungen erhalten

+ +

Um eine {{domxref("NodeList")}} aller {{HTMLElement("p")}}-Elemente des Dokuments zu erhalten:

+ +
var matches = document.querySelectorAll("p");
+ +

Das folgende Beispiel gibt eine Liste aller {{HTMLElement("div")}}-Elemente innerhalb des Dokuments zurück, deren Klasse entweder "note" oder "alert" ist:

+ +
var matches = document.querySelectorAll("div.note, div.alert");
+
+ +

Hier erhalten wir eine Liste von <p>-Elementen, deren unmittelbares übergeordnetes Element ein {{HTMLElement("div")}} mit der Klasse "highlighted" ist und die sich in einem Container befinden, dessen ID "test" ist.

+ +
var container = document.querySelector("#test");
+var matches = container.querySelectorAll("div.highlighted > p");
+ +

Das folgende Beispiel nutzt einen Attribut-Selektor, um eine Liste von {{HTMLElement("iframe")}}-Elementen im Dokument zurückzugeben, die ein "data-src" Attribut besitzen:

+ +
var matches = document.querySelectorAll("iframe[data-src]");
+ +

Hier wird ein Attribut-Selektor verwendet, um eine Aufzählung der Listenelemente zurückzugeben, die in einer Liste mit der ID "userlist" enthalten sind und deren Attribut "data-active" den Wert "1" hat:

+ +
var container = document.querySelector("#userlist");
+var matches = container.querySelectorAll("li[data-active='1']");
+ +

Auf Übereinstimmungen zugreifen

+ +

Sobald die {{domxref("NodeList")}} der übereinstimmenden Elemente zurückgegeben wird, können Sie sie wie jedes Array untersuchen. Wenn das Array leer ist (d. h. die Eigenschaft length 0 ist), wurden keine Übereinstimmungen gefunden.

+ +

Ansonsten können Sie einfach die Standard-Array-Notation verwenden, um auf den Inhalt der Liste zuzugreifen. Sie können jede allgemeine Schleifenanweisung verwenden, wie etwa:

+ +
var highlightedItems = userList.querySelectorAll(".highlighted");
+
+highlightedItems.forEach(function(userItem) {
+  deleteUser(userItem);
+});
+ +

Benutzerhinweise

+ +

querySelectorAll() verhält sich anders als die meisten JavaScript-DOM-Bibliotheken, was zu unerwarteten Ergebnissen führen kann.

+ +

HTML

+ +

Betrachten Sie dieses HTML mit seinen drei geschachtelten {{HTMLElement("div")}} Blöcken.

+ +
<div class="outer">
+  <div class="select">
+    <div class="inner">
+    </div>
+  </div>
+</div>
+ +

JavaScript

+ +
var select = document.querySelector('.select');
+var inner = select.querySelectorAll('.outer .inner');
+inner.length; // 1, not 0!
+
+ +

Wenn Sie in diesem Beispiel ".outer .inner" im Kontext des <div> mit der Klasse "select" auswählen, wird das Element mit der Klasse ".inner" immer noch gefunden, obwohl .outer kein Nachkomme des Basis-Elements ist, auf dem die Suche durchgeführt wird (".select"). Standardmäßig überprüft querySelectorAll() nur, ob sich das letzte Element im Selektor im Suchbereich befindet.

+ +

Die {{cssxref(":scope")}} Pseudo-Klasse stellt das erwartete Verhalten wieder her, bei dem Selektoren nur mit Nachkommen des Basis-Elements übereinstimmen:

+ +
var select = document.querySelector('.select');
+var inner = select.querySelectorAll(':scope .outer .inner');
+inner.length; // 0
+
+ +

Spezifikationen

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("DOM WHATWG", "#dom-parentnode-queryselectorall", "ParentNode.querySelectorAll()")}}{{Spec2("DOM WHATWG")}}Lebender Standard
{{SpecName("Selectors API Level 2", "#dom-parentnode-queryselectorall", "ParentNode.querySelectorAll()")}}{{Spec2("Selectors API Level 2")}}Keine Änderung
{{SpecName("DOM4", "#dom-parentnode-queryselectorall", "ParentNode.querySelectorAll()")}}{{Spec2("DOM4")}}Initiale Definition
{{SpecName("Selectors API Level 1", "#interface-definitions", "document.querySelector()")}}{{Spec2("Selectors API Level 1")}}Originale Definition
+ +

Browserkompatibilität

+ +
+ + +

{{Compat("api.Document.querySelectorAll")}}

+
+ +

Siehe auch

+ + diff --git a/files/de/web/api/document/readystate/index.html b/files/de/web/api/document/readystate/index.html new file mode 100644 index 0000000000..da2593e9c7 --- /dev/null +++ b/files/de/web/api/document/readystate/index.html @@ -0,0 +1,111 @@ +--- +title: Document.readyState +slug: Web/API/Document/readyState +tags: + - API + - HTML DOM + - Property + - Referenz +translation_of: Web/API/Document/readyState +--- +
{{APIRef("DOM")}} {{ gecko_minversion_header("1.9.2") }}
+ +

Zusammenfassung

+ +

Die Eigenschaft Document.readyState eines {{ domxref("document") }}-Objektes beschreibt dessen Ladezustand.

+ +

Werte

+ +

Die Eigenschaft readyState kann folgende Werte haben:

+ +
+
loading
+
Das Dokument wird noch geladen.
+
interactive
+
Das Dokument selbst wurde vollständig eingelesen und verarbeitet, aber das Laden weiterer Bestandteile wie Bilder, Stylesheets und Frames ist noch nicht abgeschlossen.
+ Dieser Status zeigt an, dass das Ereignis {{event("DOMContentLoaded")}} ausgelöst wurde.
+
complete
+
Das Dokument und seine Bestandteile wurden geladen.
+ Dieser Status zeigt an, dass das Ereignis {{event("load")}} ausgelöst wurde.
+
+ +

Ändert sich der Wert dieser Eigenschaft, wird das Ereignis {{event("readystatechange")}} des zugehörigen {{domxref("document") }}-Objekts augelöst.

+ +

Syntax

+ +
var string = document.readyState;
+
+ +

Beispiele

+ +

Verschiedene Ladezustände

+ +
switch (document.readyState) {
+  case "loading":
+    // Das Dokument wird noch geladen.
+    break;
+  case "interactive":
+    // Das Dokument wurde geladen. Wir können nun die DOM-Elemente ansprechen.
+    var span = document.createElement("span");
+    span.textContent = "A <span> element.";
+    document.body.appendChild(span);
+    break;
+  case "complete":
+    // Die Seite ist komplett geladen.
+    console.log("The first CSS rule is: " + document.styleSheets[0].cssRules[0].cssText);
+    break;
+}
+
+ +

readystatechange als eine Alternative zum Ereignis DOMContentLoaded

+ +
// Alternative zum Ereignis DOMContentLoaded
+document.onreadystatechange = function () {
+  if (document.readyState == "interactive") {
+    initApplication();
+  }
+}
+ +

readystatechange als eine Alternative zum Ereignis load

+ +
// Alternative zum Ereignis load
+document.onreadystatechange = function () {
+  if (document.readyState == "complete") {
+    initApplication();
+  }
+}
+ +

Spezifikation

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpezifikationStatusKommentar
{{SpecName("HTML WHATWG", "#current-document-readiness", "Document readiness")}}{{Spec2('HTML WHATWG')}} 
{{SpecName("HTML5.1", "#current-document-readiness", "Document readiness")}}{{Spec2('HTML5.1')}} 
{{SpecName("HTML5 W3C", "#current-document-readiness", "Document readiness")}}{{Spec2('HTML5 W3C')}}Initiale Spezifikation.
+ +

Siehe auch

+ + diff --git a/files/de/web/api/document/referrer/index.html b/files/de/web/api/document/referrer/index.html new file mode 100644 index 0000000000..8c1cd8d888 --- /dev/null +++ b/files/de/web/api/document/referrer/index.html @@ -0,0 +1,46 @@ +--- +title: Document.referrer +slug: Web/API/Document/referrer +tags: + - Referenz +translation_of: Web/API/Document/referrer +--- +
{{APIRef("DOM")}}
+ +

Gibt den URI der Seite aus, von der die aktuelle Seite aufgerufen wurde.

+ +

Syntax

+ +
var string = document.referrer;
+
+ +

Wert

+ +

Der Wert ist eine leere Zeichenkette, wenn der Benutzer direkt auf die Seite navigiert ist (nicht über einen Link, sondern z.B. über ein Lesezeichen). Da es sich bei dieser Eigenschaft lediglich um einen String handelt, ist der Zugriff auf das DOM der referenzierenden Seite nicht möglich.

+ +

Innerhalb eines {{HTMLElement("iframe")}}, wird der Document.referrer anfänglich auf den identischen Wert wie {{domxref("HTMLHyperlinkElementUtils/href", "href")}} der {{domxref("Window/location", "Window.location")}} des übergeordneten Fensters gesetzt.

+ +

Spezifikation

+ + + + + + + + + + + + + + + + +
SpezifikationStatusKommentar
{{SpecName('HTML WHATWG', '#dom-document-referrer-dev', 'document.referrer')}}{{Spec2('HTML WHATWG')}}
+ +

Browser Kompatibilität

+ + + +

{{Compat("api.Document.referrer")}}

diff --git a/files/de/web/api/document/registerelement/index.html b/files/de/web/api/document/registerelement/index.html new file mode 100644 index 0000000000..f563250e8e --- /dev/null +++ b/files/de/web/api/document/registerelement/index.html @@ -0,0 +1,113 @@ +--- +title: Document.registerElement() +slug: Web/API/Document/registerElement +tags: + - API + - DOM + - Veraltet + - Web Components +translation_of: Web/API/Document/registerElement +--- +

{{APIRef("DOM")}}

+ +
+

Warnung: document.registerElement() läuft zu Gunsten von customElements.define() aus.

+
+ +

{{draft}}

+ +

Die document.registerElement()-Methode registriert ein neues benutzerdefiniertes Element im Browser und gibt einen Konstruktor für das neue Element zurück.

+ +
+

Hinweis: Dies ist eine experimentelle Technologie. Der Browser, der sie benutzen soll, muss Web Components unterstützen. Siehe Web Components in Firefox erlauben.

+
+ +

Syntax

+ +
var constructor = document.registerElement(tag-name, options);
+ +

Parameter

+ +
+
tag-name
+
Der Name des benutzerdefinierten Elements. Der Name muss einen Bindestrich (-) enthalten, zum Beispiel my-tag.
+
options {{optional_inline}}
+
+

Ein Objekt mit den Eigenschaften prototype, auf dem das benutzerdefinierte Element basieren soll, und extends, einem bestehenden Tag, der erweitert werden soll. Beide sind optional.

+
+
+ +

Beispiel

+ +

Hier ist ein einfaches Beispiel:

+ +
var Mytag = document.registerElement('my-tag');
+
+ +

Der Tag ist num im Browser registriert. Die Mytag-Variable enthält einen Konstruktor, der benutzt werden kann, um ein my-tag-Element wie folgt im Dokument zu erzeugen:

+ +
document.body.appendChild(new Mytag());
+ +

Das fügt ein leeres my-tag-Element ein, dass sichtbar wird, wenn die Entwicklerwerkzeuge des Browsers benutzt werden aber nicht, wenn mit Hilfe des Brwoser der Quellcode betrachtet wird. So lange dem Tag kein Inhalt beigefügt wird, wird es auch in der normalen Browser-Ansicht nicht sichtbar sein. Inhalt kann beispielsweise folgendermaßen hinzugefügt werden:

+ +
var mytag = document.getElementsByTagName("my-tag")[0];
+mytag.textContent = "I am a my-tag element.";
+
+ +

Browserkompatibilität

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Grundlegende Unterstützung3531[1]{{CompatNo}}25{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Grundlegende Unterstützung4.4.431[1]{{CompatNo}}25{{CompatNo}}
+
+ +

[1] Diese API ist hinter einer Einstellung versteckt.

+ +

Siehe auch

+ + diff --git a/files/de/web/api/document/title/index.html b/files/de/web/api/document/title/index.html new file mode 100644 index 0000000000..9c54e274a6 --- /dev/null +++ b/files/de/web/api/document/title/index.html @@ -0,0 +1,70 @@ +--- +title: Document.title +slug: Web/API/Document/title +translation_of: Web/API/Document/title +--- +
{{APIRef("DOM")}}
+ +

Die Eigenschaft document.title holt oder setzt den aktuellen Titel des Dokuments.

+ +

Syntax

+ +
var docTitle = document.title;
+
+ +

docTitle ist eine Zeichenfolge, die den Titel des Dokuments enthält. Wenn der Titel durch das Setzen von document.title überschrieben wurde, enthält er diesen Wert. Andernfalls enthält er den im Markup angegebenen Titel (siehe {{Anch("Anmerkungen")}} unten).

+ +
document.title = newTitle;
+
+ +

newTitle ist der neue Titel des Dokuments. Die Zuweisung beeinflusst den Rückgabewert von document.title, den für das Dokument angezeigten Titel (z.B. in der Titelleiste des Fensters oder Tabs), und sie beeinflusst auch das DOM des Dokuments (z.B. den Inhalt des Elements <title> in einem HTML-Dokument).

+ +

Beispiel

+ +
<!DOCTYPE html>
+<html>
+<head>
+  <title>Hallo Welt!</title>
+</head>
+<body>
+
+  <script>
+    alert(document.title); // zeigt "Hallo Welt!"
+    document.title = "Tschüss Welt!";
+    alert(document.title); // zeigt "Tschüss Welt!"
+  </script>
+
+</body>
+</html>
+
+ +

Anmerkungen

+ +

Diese Eigenschaft gilt für HTML-, SVG-, XUL- und andere Dokumente in Gecko.

+ +

Bei HTML-Dokumenten ist der Anfangswert von document.title der Textinhalt des Elements <title>. Bei XUL ist es der Wert des {{XULAttr("title")}} Attributs des {{XULElem("window")}} oder eines anderen XUL-Elements der obersten Ebene.

+ +

In XUL hat der Zugriff auf document.title, bevor das Dokument vollständig geladen ist, ein undefiniertes Verhalten: document.title gibt möglicherweise eine leere Zeichenfolge zurück, und das Setzen von document.title hat möglicherweise keine Wirkung.

+ +

Spezifikationen

+ + + + + + + + + + + + + + +
SpezifikationStatusKommentar
{{SpecName('HTML WHATWG','#document.title','document.title')}}{{Spec2('HTML WHATWG')}}
+ +

Browser-Kompatibilität

+ + + +

{{Compat("api.Document.title")}}

diff --git a/files/de/web/api/document/url/index.html b/files/de/web/api/document/url/index.html new file mode 100644 index 0000000000..29770925ee --- /dev/null +++ b/files/de/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")}}
+ +

Die schreibgeschützte Eigenschaft URL des {{domxref("Document")}} interface gibt den Ort des Dokuments als String zurück.

+ +

Syntax

+ +
var string = document.URL
+
+ +

Spezifikation

+ + diff --git a/files/de/web/api/document/width/index.html b/files/de/web/api/document/width/index.html new file mode 100644 index 0000000000..5fc3e1c80a --- /dev/null +++ b/files/de/web/api/document/width/index.html @@ -0,0 +1,45 @@ +--- +title: Document.width +slug: Web/API/Document/width +translation_of: Web/API/Document/width +--- +
{{APIRef("DOM")}} {{Obsolete_header}}
+ +
+

Note: Starting in {{Gecko("6.0")}}, document.width is no longer supported. Instead, use document.body.clientWidth. See {{domxref("element.clientWidth")}}.

+
+ +

Gibt die Breite des {{HTMLElement("body")}} Elements des aktuellen Dokuments in Pixeln zurück.

+ +

Wird nicht vom Internet Explorer unterstützt.

+ +

Syntax

+ +
pixels = document.width;
+
+ +

Beispiel

+ +
function init() {
+    alert("Die Breite des Dokuments beträgt " + document.width + " Pixel.");
+}
+
+ +

Alternativen

+ +
document.body.clientWidth              /* Breite des <body> */
+document.documentElement.clientWidth   /* Breite des <html> */
+window.innerWidth                      /* Breite des Browserfensters */
+
+ +

Spezifikation

+ +

HTML5

+ +

Siehe auch

+ + diff --git a/files/de/web/api/document/write/index.html b/files/de/web/api/document/write/index.html new file mode 100644 index 0000000000..3b25f6b658 --- /dev/null +++ b/files/de/web/api/document/write/index.html @@ -0,0 +1,85 @@ +--- +title: Document.write() +slug: Web/API/Document/write +tags: + - API + - DOM + - Document + - Méthode + - Referenz +translation_of: Web/API/Document/write +--- +
{{ ApiRef("DOM") }}
+ +

Schreibt eine Zeichenfolge in einen Dokument-Stream, der zuvor mittels document.open() geöffnet wurde.

+ +
Hinweis: da document.write in einen Dokument-Stream schreibt, wird beim Aufruf von document.write auf ein geschlossenes (fertig geladenes) Dokument dieses automatisch wieder mittels document.open geöffnet, wodurch das Dokument geleert wird.
+ +

Syntax

+ +
document.write(markup);
+
+ +

Parameter

+ +
+
markup
+
Ein String, der in das Dokument geschrieben wird.
+
+ +

Beispiel

+ +
<html>
+
+<head>
+  <title>write example</title>
+
+  <script>
+    function newContent() {
+      alert("load new content");
+      document.open();
+      document.write("<h1>Raus mit dem Alten - rein mit dem Neuen!</h1>");
+      document.close();
+    }
+  </script>
+</head>
+
+<body onload="newContent();">
+  <p>originaler Dokumenten-Inhalt</p>
+</body>
+
+</html>
+
+ +

Hinweise

+ +

Wird die Ausgabe auf ein Dokument angewendet, das zuvor nicht mittels document.open() geöffnet wurde, löst dies ein implizites document.open aus. Sobald Sie den Schreibvorgang beendet haben, empfiehlt es sich document.close() aufzurufen, um dem Browser mitzuteilen, dass das Dokument vollständig geladen werden kann. Der geschriebene Text wird in das Strukturmodell des Dokuments eingelesen. Im vorherigen Beispiel wird das h1-Element automatisch in einen Knoten im Dokument umgewandelt.

+ +

Wird der document.write() Aufruf in ein im HTML eingeschlossenes <script> Tag eingebunden, wird document.open() nicht aufgerufen. Zum Beispiel:

+ +
<script>
+  document.write("<h1>Main title</h1>")
+</script>
+
+ +
Hinweis: document.write und document.writeln funktionieren nicht in XHTML Documenten (Sie erhalten einen "Operation is not supported" [NS_ERROR_DOM_NOT_SUPPORTED_ERR] Fehler in der Fehlerkonsole). Dies tritt auf, sobald Sie eine lokale Datei mit der Erweiterung .xhtml laden oder eine Datei öffnen, die mit dem application/xhtml+xml-MIME-Typ vom Server gesendet wurde. Weitere Informationen erhalten Sie in der W3C XHTML FAQ.
+ +
Hinweis: document.write in verzögert geladenen oder asynchronen Scripten wird ignoriert und Sie erhalten eine Nachricht ähnlich dieser in der Fehlerkonsole: "A call to document.write() from an asynchronously-loaded external script was ignored".
+ +
Hinweis (Nur Microsoft Edge): ein wiederholter Aufruf vondocument.write in einem <iframe> erzeugt den Fehler "SCRIPT70: Permission denied".
+ +
Hinweis (Chrome Version 55+): per document.write() injizierte <script>-Elemente werden bei einer 2G Verbindung nach einem HTTP Cache Miss nicht ausgeführt.
+ +

Spezifikationen

+ + + +

Siehe auch

+ + diff --git a/files/de/web/api/document/writeln/index.html b/files/de/web/api/document/writeln/index.html new file mode 100644 index 0000000000..6581924105 --- /dev/null +++ b/files/de/web/api/document/writeln/index.html @@ -0,0 +1,60 @@ +--- +title: Document.writeln() +slug: Web/API/Document/writeln +translation_of: Web/API/Document/writeln +--- +

{{ ApiRef("DOM") }}

+ +

Schreibt eine Textfolge, gefolgt von einem Zeilenumbruchzeichen, in ein Dokument.

+ +

Syntax

+ +
document.writeln(line);
+
+ +

Parameters

+ + + +

Beispiel

+ +
document.writeln("<p>enter password:</p>");
+
+ +

Notes

+ +

document.writeln ist dasselbe wie {{domxref("document.write")}} aber fügt einen Zeilenumbruch hinzu.

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

Spezifikation

+ + + + + + + + + + + + + + + + + + + + + +
SpezifikationStatusBemerkung
{{SpecName("HTML WHATWG", "#dom-document-writeln", "document.writeln()")}}{{Spec2("HTML WHATWG")}}
{{SpecName("DOM2 HTML", "html.html#ID-35318390", "document.writeln()")}}{{Spec2("DOM2 HTML")}}
+ +

Browser Kompatibilität

+ + + +

{{Compat("api.Document.writeln")}}

diff --git a/files/de/web/api/documentfragment/index.html b/files/de/web/api/documentfragment/index.html new file mode 100644 index 0000000000..8dc6abcceb --- /dev/null +++ b/files/de/web/api/documentfragment/index.html @@ -0,0 +1,258 @@ +--- +title: DocumentFragment +slug: Web/API/DocumentFragment +tags: + - API + - DOM + - DocumentFragment + - Documents + - Interface + - Reference + - Web Components +translation_of: Web/API/DocumentFragment +--- +
{{ APIRef("DOM") }}
+ +

Das DocumentFragment interface stellt ein einfaches Objekt dar, welches ohne Bezug zu einem parent erstellt und verwendet werden kann. Es kann somit verstanden werden als eine leichtgewichtige Variante des {{domxref("Document")}}, die einen Ausschnitt einer Dokumentstruktur aus Element-Knoten abbildet. Der zentrale Unterschied dabei ist jedoch, dass das Fragment nicht Bestandteil der aktiven Seitenstruktur und des DOM-Baums ist. Dadurch haben Änderungen an dem Fragment keine Auswirkungen auf das aktive Dokument, wodurch unerwünschte Seiteneffekte von DOM-Änderungen wie {{Glossary("reflow")}} oder Performanceeinbußen verhindert werden können.

+ +

Üblicherweise wird das DocumentFragment dazu verwendet, um einen neuen DOM-Teilbaum für eine Seite zu erzeugen und darin beliebig Fragmente und Knoten vorbereiten zu können, diese über das {{domxref("Node")}} interface mittels Methoden wie {{domxref("Node.appendChild", "appendChild()")}} und {{domxref("Node.insertBefore", "insertBefore()")}} hinzuzufügen. Wenn das Frament schließlich in die aktive Dokumentstruktur und deren DOM eingefügt wird, bleibt ein leeres DocumentFragment zurück. Da alle Knoten auf einmal in das aktive Dokument hinzugefügt werden, wird lediglich ein einzelner reflow und render Prozess ausgelöst, anstelle von potentiell unzähligen für jeden einzelnen, separat eingefügten Knoten.

+ +

Das interface wird ebenso bei Web components verwendet: {{HTMLElement("template")}}-Elemente beinhalten ein DocumentFragment in ihrer {{domxref("HTMLTemplateElement.content")}} Eigenschaft.

+ +

Ein leeres DocumentFragment kann jederzeit erzeugt werden über {{domxref("document.createDocumentFragment()")}} oder über den constructor.

+ +

{{InheritanceDiagram}}

+ +

Eigenschaften

+ +

Das interface hat keine spezifischen Eigenschaften, erhält jedoch über Vererbung die des übergeordneten {{domxref("Node")}} und implementiert darüber hinaus jene des {{domxref("ParentNode")}} interfaces zusätzlich.

+ +
+
{{ domxref("ParentNode.children") }} {{readonlyInline}}{{experimental_inline}}
+
Stellt eine aktuelle {{domxref("HTMLCollection")}} bereit mit allen {{domxref("Element")}} Objekten, die dem DocumentFragment angehören.
+
{{ domxref("ParentNode.firstElementChild") }} {{readonlyInline}}{{experimental_inline}}
+
Stellt das {{domxref("Element")}} bereit, welches aktuell das erste Kind des DocumentFragment ist. null falls es keines gibt.
+
{{ domxref("ParentNode.lastElementChild") }} {{readonlyInline}}{{experimental_inline}}
+
Stellt das {{domxref("Element")}} bereit, welches aktuell das letzte Kind des DocumentFragment ist. null falls es keines gibt.
+
{{ domxref("ParentNode.childElementCount") }} {{readonlyInline}}{{experimental_inline}}
+
Stellt als unsigned long die Anzahl der Kindelemente des DocumentFragment bereit.
+
+ +

Constructor

+ +
+
{{ domxref("DocumentFragment.DocumentFragment()", "DocumentFragment()") }} {{experimental_inline}}
+
Erzeugt ein neues, leeres DocumentFragment Objekt.
+
+ +

Methoden

+ +

Das interface erbt die Methoden von {{domxref("Node")}}, und implementiert darüber hinaus jene des {{domxref("ParentNode")}} interfaces zusätzlich.

+ +
+
{{domxref("DocumentFragment.find()")}} {{experimental_inline}}
+
Liefert das erste zutreffende {{domxref("Element")}} innerhalb des Baums des DocumentFragment.
+
{{domxref("DocumentFragment.findAll()")}} {{experimental_inline}}
+
Liefert eine {{domxref("NodeList")}} mit allen zutreffenden {{domxref("Element")}} innerhalb des Baums des DocumentFragment.
+
{{domxref("DocumentFragment.querySelector()")}}
+
Liefert den {{domxref("Element")}} Knoten im DocumentFragment, der in der Reihenfolge im document als erstes zu dem Selektor passt.
+
{{domxref("DocumentFragment.querySelectorAll()")}}
+
Liefert eine {{domxref("NodeList")}} mit allen {{domxref("Element")}} Knoden im DocumentFragment, die zu dem angegebenen Selektor passen.
+
+ +
+
{{domxref("DocumentFragment.getElementById()")}}
+
Liefert den ersten {{domxref("Element")}} Knoten im DocumentFragment, dem in der document Reihenfolge zuerst die angegebene ID zugeordnet ist.
+
+ +

Spezifikationen

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpezifikationStatusAnmerkungen
{{SpecName('DOM WHATWG', '#interface-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
+ +

Browserkompatibilität

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support1.0{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.0")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
querySelector() and querySelectorAll()1.0{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.9.1")}}8.010.03.2 (525.3)
findAll() and find() {{experimental_inline}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
DocumentFragment() constructor {{experimental_inline}}28.0{{CompatVersionUnknown}}{{CompatGeckoDesktop("24.0")}}{{CompatNo}}15.0{{CompatNo}}
ParentNode properties {{experimental_inline}}28.0{{CompatNo}}{{CompatGeckoDesktop("25.0")}}{{CompatNo}}15.0{{CompatNo}}
ParentNode methods {{experimental_inline}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("1.0")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
querySelector() and querySelectorAll()2.1{{CompatVersionUnknown}}{{CompatGeckoMobile("1.0")}}8.010.03.2 (525.3)
findAll() and find() {{experimental_inline}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
DocumentFragment() constructor {{experimental_inline}}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("24.0")}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}
ParentNode properties {{experimental_inline}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatGeckoMobile("25.0")}}{{CompatNo}}5.0{{CompatNo}}
ParentNode methods {{experimental_inline}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

See also

+ + diff --git a/files/de/web/api/domerror/index.html b/files/de/web/api/domerror/index.html new file mode 100644 index 0000000000..1251609ed3 --- /dev/null +++ b/files/de/web/api/domerror/index.html @@ -0,0 +1,189 @@ +--- +title: DOMError +slug: Web/API/DOMError +tags: + - API + - DOM + - Fehler + - Interface + - Referenz +translation_of: Web/API/DOMError +--- +

{{ APIRef("DOM") }}

+ +

Das DOMError-Interface beschreibt ein Fehler-Objekt, welches ein Fehlername enthält.

+ +

Eigenschaften

+ +
+
{{domxref("DOMError.name")}} {{readOnlyInline}}
+
Gibt ein {{ domxref("DOMString") }} zurück, welcher einer der folgenden Fehlertypnamen repäsentiert (siehe unten).
+
+ +

Fehlertypen

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
TypBeschreibung
IndexSizeErrorDer Index ist ausserhalb des gültigen Bereichs (z. B. bei einem {{ domxref("range") }}-Objekt).
HierarchyRequestErrorDie  Knoten-Baum-Hierarchie ist nicht korrekt.
WrongDocumentErrorDas Objekt ist im falschen {{ domxref("document") }}.
InvalidCharacterErrorDer String beeinhaltet unglütige Charakter.
NoModificationAllowedErrorDas Objekt kann nicht modifiziert werden.
NotFoundErrorDas Objekt kann nicht gefunden werden.
NotSupportedErrorDie Operation wird nicht unterstützt
InvalidStateErrorDas Objekt hat einen ungültigen Status.
SyntaxErrorDer String entspricht nicht den erwarteten Muster.
InvalidModificationErrorDas Objekt kann nicht in dieser Art modifiziert werden.
NamespaceErrorDie Operation ist nicht erlaubt in XML-Namespaces.
InvalidAccessErrorDas Objekt unterstützt diese Operation oder dieses Argument nicht.
TypeMismatchErrorDer Typ des Objekts entspricht nicht dem erwarteten Typ.
SecurityErrorDiese Operation ist unsicher.
NetworkErrorEin Netzwerkfehler ist aufgetreten.
AbortErrorDie Operation wurde abgebrochen.
URLMismatchErrorDie angegebene URL entspricht nicht einer anderen URL.
QuotaExceededErrorDas Kontingent wurde überschritten.
TimeoutErrorTimeout bei der Operation.
InvalidNodeTypeErrorDer Knoten ist nicht korrekt oder hat falsche Vorfahren für die Operation.
DataCloneErrorDas Objekt kann nicht geklont werden.
+ +

Spezifikationen

+ + + + + + + + + + + + + + +
SpezifikationStatusKommentar
{{SpecName('DOM4', '#interface-domerror', 'DOMError')}}{{Spec2('DOM4')}}Initial definition.
+ +

Browser-Kompatiblität

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basissupport{{CompatUnknown}}12.0{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basissupport{{CompatUnknown}}12.0{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

Siehe auch

+ + diff --git a/files/de/web/api/domparser/index.html b/files/de/web/api/domparser/index.html new file mode 100644 index 0000000000..8082197658 --- /dev/null +++ b/files/de/web/api/domparser/index.html @@ -0,0 +1,181 @@ +--- +title: DOMParser +slug: Web/API/DOMParser +translation_of: Web/API/DOMParser +--- +

{{APIRef("DOM")}}{{SeeCompatTable}}

+ +

Der DOMParser kann XML oder HTML aus einem String in ein DOM-Document parsen. Der DOMParser ist spezifiziert in DOM Parsing and Serialization.

+ +

XMLHttpRequest unterstützt das parsen von XML- und HTML-Dokumenten auf die über eine URL zugegriffen wird.

+ +

DOMParser erzeugen

+ +

Um einen neuen DOMParser zu erzeugen benutze einfach new DOMParser().

+ +

Für mehr Informationen über das Erstellen von einem DOMParser in einer Firefox-Erweiterung, konsultiere die nsIDOMParser-Dokumentation.

+ +

XML parsen

+ +

Nachdem du einmal ein Parser-Objekt erzeugt hast, kannst du XML-Strings mit der parseFromString-Methode parsen.

+ +
const parser = new DOMParser();
+const doc = parser.parseFromString(stringContainingXMLSource, "application/xml");
+
+ +

Fehlerbehandlung

+ +

Beachte dass derzeit keine Exception ausgelöst wird, wenn es beim Ausführen des Parser-Prozesses zu einem Fehler kommen sollte. Stattdessen wird ein Fehler-Dokument  (s.a. {{Bug(45566)}}) ausgelöst:

+ +
<parsererror xmlns="http://www.mozilla.org/newlayout/xml/parsererror.xml">
+(error description)
+<sourcetext>(a snippet of the source XML)</sourcetext>
+</parsererror>
+
+ +

Die Parsing-Fehler werden auch in der Error-Console, zusammen mit dem Dokument-URl als Fehlerquelle ausgegeben (s.u.).

+ +

Ein SVG- oder HTML-Dokument parsen

+ +

Der DOMParser beherrscht auch SVG {{geckoRelease("10.0")}} und HTML {{geckoRelease("12.0")}}. Es gibt drei mögliche Ergebnisse, die mit der Übergabe eines MIME-Typen ausgewählt werden können. Ist der MIME-Typ text/xml, ist das resultierende Dokument ein XMLDocument, ist er image/svg+xml, wird ein SVGDocument zurückgegeben und für text/html erhält man ein HTMLDocument.

+ +
const xmlDoc = new DOMParser().parseFromString(stringContainingXMLSource, "application/xml");
+// returns a Document, but not a SVGDocument nor a HTMLDocument
+
+const svgDoc = new DOMParser().parseFromString(stringContainingXMLSource, "image/svg+xml");
+// returns a SVGDocument, which also is a Document.
+
+const htmlDoc = new DOMParser().parseFromString(stringContainingHTMLSource, "text/html");
+// returns a HTMLDocument, which also is a Document.
+
+ +

DOMParser HTML-Erweiterung für andere Browser

+ +
/* inspiriert von https://gist.github.com/1129031 */
+/*global document, DOMParser*/
+
+(function(DOMParser) {
+    "use strict";
+
+    const proto = DOMParser.prototype;
+    const nativeParse = proto.parseFromString;
+
+    // Firefox/Opera/IE werfen bei unbekannten Typen Fehler
+    try {
+        // WebKit gibt bei bei unbekannten Typen `null` zurück
+        if (new DOMParser().parseFromString("", "text/html")) {
+            // text/html wird unterstützt
+            return;
+        }
+    } catch (ex) {}
+
+    proto.parseFromString = function(markup, type) {
+        if (/^\s*text\/html\s*(?:;|$)/i.test(type)) {
+            const doc = document.implementation.createHTMLDocument("");
+            if (markup.toLowerCase().includes('<!doctype')) {
+                doc.documentElement.innerHTML = markup;
+            } else {
+                doc.body.innerHTML = markup;
+            }
+            return doc;
+        } else {
+            return nativeParse.apply(this, arguments);
+        }
+    };
+}(DOMParser));
+
+ +

Den DOMParser im Chrome/JSM/XPCOM/Privileged-Scope aufrufen

+ +

Siehe nsIDOMParser

+ +

Browser-Kompatibilität

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
XML support{{CompatChrome(1)}}{{CompatGeckoDesktop(1)}}{{CompatIE(9)}}{{CompatOpera(8)}}{{CompatSafari(3.2)}}
SVG support{{CompatChrome(4)}}{{CompatGeckoDesktop(10.0)}}{{CompatIE(10)}}{{CompatOpera(15)}}{{CompatSafari(3.2)}}
HTML support{{CompatChrome(30)}}{{CompatGeckoDesktop(12.0)}}{{CompatIE(10)}}{{CompatOpera(17)}}{{CompatSafari(7.1)}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
XML support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}
SVG support{{CompatUnknown}}{{CompatGeckoMobile(10.0)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
HTML support{{CompatUnknown}}{{CompatGeckoMobile(12.0)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

Siehe auch

+ + diff --git a/files/de/web/api/domstring/index.html b/files/de/web/api/domstring/index.html new file mode 100644 index 0000000000..e6b148275c --- /dev/null +++ b/files/de/web/api/domstring/index.html @@ -0,0 +1,57 @@ +--- +title: DOMString +slug: Web/API/DOMString +tags: + - API + - DOM + - DOM Referenz + - DOMString + - Referenz + - String +translation_of: Web/API/DOMString +--- +

{{APIRef("DOM")}}

+ +

DOMString ist ein UTF-16 String. Obwohl JavaScript bereits solche Strings nutzt wird DOMString direkt zu einem {{jsxref("String")}} gemappt.

+ +

Wird null in einem Parameter oder einer Methode übergeben, so wandelt DOMString dies in den String "null" um.

+ +

Spezifikationen

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpezifikationStatusKommentar
{{SpecName('WebIDL', '#idl-DOMString', 'DOMString')}}{{Spec2('WebIDL')}}Anpassung der Definition um
{{SpecName('DOM3 Core', 'core.html#DOMString', 'DOMString')}}{{Spec2('DOM3 Core')}}Keine Änderung von {{SpecName('DOM2 Core')}}
{{SpecName('DOM2 Core', 'core.html#ID-C74D1578', 'DOMString')}}{{Spec2('DOM2 Core')}}Keine Änderung von {{SpecName('DOM1')}}
{{SpecName('DOM1', 'level-one-core.html#ID-C74D1578', 'DOMString')}}{{Spec2('DOM1')}}Ursprüngliche Definition.
+ +

See also

+ + diff --git a/files/de/web/api/domtokenlist/add/index.html b/files/de/web/api/domtokenlist/add/index.html new file mode 100644 index 0000000000..2e1b6728c2 --- /dev/null +++ b/files/de/web/api/domtokenlist/add/index.html @@ -0,0 +1,73 @@ +--- +title: DOMTokenList.add() +slug: Web/API/DOMTokenList/add +translation_of: Web/API/DOMTokenList/add +--- +

{{APIRef("DOM")}}

+ +

Die add() Methode des {{domxref("DOMTokenList")}} Interfaces, fügt ein token der Liste an.

+ +

Syntax

+ +
tokenList.add(token1[, token2[, ...]]);
+ +

Parameter

+ +
+
token
+
Ein {{domxref("DOMString")}} ,welches das token repräsentiert, welches an die Liste angefügt werden soll.
+
+ +

Rückgabewert

+ +

undefined

+ +

Beispiele

+ +

Im folgenden Beispiel erhalten wir die Liste der Klassen eines {{htmlelement("span")}} Elementes als DOMTokenList  , mit Hilfe von {{domxref("Element.classList")}}. Wir fügen der Liste dann ein neues token an und schreiben die Liste als inhalt in das <span>.

+ +

Das HTML:

+ +
<span class="a b c"></span>
+ +

Nun das JavaScript:

+ +
var span = document.querySelector("span");
+var classes = span.classList;
+classes.add("d");
+span.textContent = classes;
+
+ +

Die Ausgabe:

+ +

{{ EmbedLiveSample('Examples', '100%', 60) }}

+ +

Man kann auch mehrere tokens auf einmal hinzufügen:

+ +
span.classList.add("d", "e", "f");
+
+ +

Spezifikationen

+ + + + + + + + + + + + + + +
SpezifikationStatusKommentar
{{SpecName('DOM WHATWG','#dom-domtokenlist-add','add()')}}{{Spec2('DOM WHATWG')}}Initial definition
+ +

Browser Kompatibilität

+ +
+ + +

{{Compat("api.DOMTokenList.add")}}

+
diff --git a/files/de/web/api/domtokenlist/index.html b/files/de/web/api/domtokenlist/index.html new file mode 100644 index 0000000000..c963c053e0 --- /dev/null +++ b/files/de/web/api/domtokenlist/index.html @@ -0,0 +1,125 @@ +--- +title: DOMTokenList +slug: Web/API/DOMTokenList +translation_of: Web/API/DOMTokenList +--- +

{{APIRef("DOM")}}{{gecko_minversion_header("1.9.2")}}

+ +

Die DOMTokenList Schnittstelle repräsentiert eine Sammlung von durch Leerzeichen getrennte Zeichen/ Merkmale (Tokens). Solch eine Ansammlung wird wiedergegben von {{domxref("Element.classList")}}, {{domxref("HTMLLinkElement.relList")}}, {{domxref("HTMLAnchorElement.relList")}} oder {{domxref("HTMLAreaElement.relList")}}. Deren Index beginnt bei 0 wie bei JavaScript {{jsxref("Array")}} Objekten. DOMTokenList achten immer auf die Groß- und Kleinschreibung.

+ +

Eigenschaften

+ +

Die Schnittstelle erbt keine Eigenschaften.

+ +
+
{{domxref("DOMTokenList.length")}} {{ReadOnlyInline}}
+
Ist eine Ganzzahl, die die Anzahl der im Objekt gespeicherten Objekte darstellt.
+
+ +

Methoden

+ +

Diese Schnittstelle erbt keine Methode.

+ +
+
{{domxref("DOMTokenList.item()")}}
+
Returns an item in the list by its index (or undefined if the number is greater than or equal to the length of the list, prior to {{gecko("7.0")}} returned null)
+
{{domxref("DOMTokenList.contains()")}}
+
Returns true if the underlying string contains token, otherwise false
+
{{domxref("DOMTokenList.add()")}}
+
Fügt token der Liste hinzu.
+
{{domxref("DOMTokenList.remove()")}}
+
Removes token from the underlying string
+
{{domxref("DOMTokenList.replace()")}}
+
Replaces an existing token with a new token.
+
{{domxref("DOMTokenList.supports()")}}
+
Returns true if a given token is in the associated attribute's supported tokens.
+
{{domxref("DOMTokenList.toggle()")}}
+
Removes token from string and returns false. If token doesn't exist it's added and the function returns true
+
{{domxref("DOMTokenList.entries()")}}
+
Returns an {{jsxref("Iteration_protocols","iterator")}} allowing to go through all key/value pairs contained in this object.
+
{{domxref("DOMTokenList.forEach()")}}
+
Executes a provided function once per DOMTokenList element.
+
{{domxref("DOMTokenList.keys()")}}
+
Returns an {{jsxref("Iteration_protocols", "iterator")}} allowing to go through all keys of the key/value pairs contained in this object.
+
{{domxref("DOMTokenList.values()")}}
+
Returns an {{jsxref("Iteration_protocols", "iterator")}} allowing to go through all values of the key/value pairs contained in this object.
+
+ +

Spezifikationen

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("DOM WHATWG", "#interface-domtokenlist", "DOMTokenList")}}{{Spec2("DOM WHATWG")}}Initial definition
+ +

Browserkompatibilität

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}10{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)IE PhoneOpera MobileSafari MobileChrome for Android
Basic support{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}
+
+ +

Siehe auch

+ + diff --git a/files/de/web/api/dragevent/index.html b/files/de/web/api/dragevent/index.html new file mode 100644 index 0000000000..4f6ec7b562 --- /dev/null +++ b/files/de/web/api/dragevent/index.html @@ -0,0 +1,239 @@ +--- +title: DragEvent +slug: Web/API/DragEvent +translation_of: Web/API/DragEvent +--- +
{{APIRef("HTML DOM")}}
+ +

Das drag Event wird ausgelöst, wenn ein Element oder ein Text "gezogen" wird (alle paar hundert Millisekunden).

+ +

Allgemeine Informationen

+ +
+
Spezifikation
+
HTML5
+
Interface
+
DragEvent
+
Steigt auf
+
Ja
+
Abbrechbar
+
Ja
+
Ziel
+
Document, Element
+
Standard-Aktion
+
Mit der drag & drop Operation fortfahren.
+
+ +

Eigenschaften

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PropertyTypeDescription
target {{readonlyInline}}EventTargetThe element that was underneath the element being dragged.
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.
dataTransferDataTransferThe data that underlies a drag-and-drop operation, known as the drag data store. Protected mode.
currentTarget {{readonlyInline}}EventTargetThe node that had the event listener attached.
relatedTarget {{readonlyInline}}EventTargetFor 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.
+ +

Beispiel

+ +
<div class="dropzone">
+    <div id="draggable" draggable="true" ondragstart="event.dataTransfer.setData('text/plain',null)">
+        This div is draggable
+    </div>
+</div>
+<div class="dropzone"></div>
+<div class="dropzone"></div>
+<div class="dropzone"></div>
+
+<style>
+  #draggable {
+    width: 200px;
+    height: 20px;
+    text-align: center;
+    background: white;
+  }
+
+  .dropzone {
+    width: 200px;
+    height: 20px;
+    background: blueviolet;
+    margin-bottom: 10px;
+    padding: 10px;
+  }
+</style>
+
+<script>
+  var dragged;
+
+  /* Event wird vom ge-drag-ten Element ausgelöst */
+  document.addEventListener("drag", function( event ) {
+
+  }, false);
+
+  document.addEventListener("dragstart", function( event ) {
+      // Speichern einer ref auf das drag-bare Element
+      dragged = event.target;
+      // Element halb-transparent machen
+      event.target.style.opacity = .5;
+  }, false);
+
+  document.addEventListener("dragend", function( event ) {
+      // Transparenz zurücksetzen
+      event.target.style.opacity = "";
+  }, false);
+
+  /* events fired on the drop targets */
+  document.addEventListener("dragover", function( event ) {
+      // Standard-Aktion verhindern um das drop-Event zu erlauben
+      event.preventDefault();
+  }, false);
+
+  document.addEventListener("dragenter", function( event ) {
+      // Hintergrund des möglichen Drop-Zeils anfärben, wenn das drag-bare Element auf das Ziel gezogen wird
+      if ( event.target.className == "dropzone" ) {
+          event.target.style.background = "purple";
+      }
+
+  }, false);
+
+  document.addEventListener("dragleave", function( event ) {
+      // Hintergrund des möglichen Drop-Ziels, wenn das drag-bare Element vom Ziel wieder weggezogen wird / verlässt
+      if ( event.target.className == "dropzone" ) {
+          event.target.style.background = "";
+      }
+  }, false);
+
+  document.addEventListener("drop", function( event ) {
+      // Standard-Aktion verhindern (Bei einigen Elementen wäre das das Öffnen als Link)
+      event.preventDefault();
+      // move dragged elem to the selected drop target
+      if ( event.target.className == "dropzone" ) {
+          event.target.style.background = "";
+          dragged.parentNode.removeChild( dragged );
+          event.target.appendChild( dragged );
+      }
+
+  }, false);
+</script>
+
+ +

Verwandte Events

+ +

 

+ + + +

 

diff --git a/files/de/web/api/element/classlist/index.html b/files/de/web/api/element/classlist/index.html new file mode 100644 index 0000000000..4e1f9b25df --- /dev/null +++ b/files/de/web/api/element/classlist/index.html @@ -0,0 +1,300 @@ +--- +title: Element.classList +slug: Web/API/Element/classList +translation_of: Web/API/Element/classList +--- +
{{APIRef("DOM")}}
+ +

Das Element.classList ist eine read-only Eigenschaft, welche die aktuelle {{domxref("DOMTokenList")}} Sammlung der Klassen-Attribute des Elements zurückgibt.

+ +

Die Benutzung von classList ist eine angenehme Alternative zum Ansprechen der Klassen eines Elements als die leerzeichengetrennte Zeichenfolge via {{domxref("element.className")}}. 

+ +

Syntax

+ +
const elementClasses = elementNodeReference.classList;
+
+ +

elementClasses ist eine DOMTokenList, welche die Klassen-Attribute der elementNodeReference repräsentiert. Wenn das Klassen-Attribut nicht gesetzt wurde oder elementClasses.length leer ist, wird 0 zurückgegeben. Element.classList selbst ist nur lesbar (read-only), obgleich es modifiziert werden kann, indem die Methoden add() und remove() angewendet werden.

+ +

Methoden

+ +
+
add( String [, String [, ...]] )
+
Fügt angegebene Klassenwerte hinzu. Wenn diese Klassen bereits im Attribut des Elements vorhanden sind, werden sie ignoriert.
+
remove( String [, String [, ...]] )
+
Ausgewählte Klassenwerte entfernen.
+ Bemerkung: Entfernen eines nicht vorhandenen Klassenwertes wirft keinen Fehler.
+
item ( Number )
+
Rückgabewert nach Index in der Sammlung.
+
toggle ( String [, force] )
+
Wenn nur ein Argument vorhanden ist: Klassenwert umschalten; d.h. wenn die Klasse existiert, dann entfernt es diese und gibt false zurück, wenn nicht, dann fügt es diese hinzu und gibt true zurück.
+
Wenn ein zweites Argument vorhanden ist: Wenn das zweite Argument auf true basiert, fügt es den angegebenen Klassenwert hinzu. Wenn es false auswertet, entfernt es ihn.
+
contains( String )
+
Überprüft, ob der angegebene Klassenwert im Klassenattribut des Elements vorhanden ist.
+
replace( oldClass, newClass )
+
Ersetzt einen vorhandenen Klassenwert.
+
+ +

Beispiele

+ +
const div = document.createElement('div');
+div.className = 'foo';
+
+// Status zum Beginn: <div class="foo"></div>
+console.log(div.outerHTML);
+
+// classList-API zum Entfernen und Ergänzen von Klassen nutzen
+div.classList.remove("foo");
+div.classList.add("anotherclass");
+
+// <div class="anotherclass"></div>
+console.log(div.outerHTML);
+
+// Wenn visible gesetzt ist entferne es, sonst füge es hinzu
+div.classList.toggle("visible");
+
+// Hinzufügen/Enfernen von visible, abhängig von der Bedingung, ob i kleiner 10 ist
+div.classList.toggle("visible", i < 10 );
+
+console.log(div.classList.contains("foo"));
+
+// Mehrere Klassen hinzufügen / entfernen
+div.classList.add("foo", "bar", "baz");
+div.classList.remove("foo", "bar", "baz");
+
+// Mehrere Klassen mittels Spread-Syntax hinzufügen / entfernen
+const cls = ["foo", "bar"];
+div.classList.add(...cls);
+div.classList.remove(...cls);
+
+// Klasse "foo" durch "bar" ersetzen
+div.classList.replace("foo", "bar");
+ +
+

Firefox-Versionen vor 26 setzen nicht die Nutzung die Nutzung von mehreren Argumenten in den Methoden add/remove/toggle um. Siehe https://bugzilla.mozilla.org/show_bug.cgi?id=814014

+
+ +

Polyfill

+ +
// Source: https://gist.github.com/k-gun/c2ea7c49edf7b757fe9561ba37cb19ca
+/**
+ * Element.prototype.classList for IE8/9, Safari.
+ * @author    Kerem Güneş <k-gun@mail.com>
+ * @copyright Released under the MIT License <https://opensource.org/licenses/MIT>
+ * @version   1.2
+ * @see       https://developer.mozilla.org/en-US/docs/Web/API/Element/classList
+ */
+;(function() {
+    // Helpers.
+    var trim = function(s) {
+            return s.replace(/^\s+|\s+$/g, '');
+        },
+        regExp = function(name) {
+            return new RegExp('(^|\\s+)'+ name +'(\\s+|$)');
+        },
+        forEach = function(list, fn, scope) {
+            for (var i = 0; i < list.length; i++) {
+                fn.call(scope, list[i]);
+            }
+        };
+
+    // Class list object with basic methods.
+    function ClassList(element) {
+        this.element = element;
+    }
+
+    ClassList.prototype = {
+        add: function() {
+            forEach(arguments, function(name) {
+                if (!this.contains(name)) {
+                    this.element.className = trim(this.element.className +' '+ name);
+                }
+            }, this);
+        },
+        remove: function() {
+            forEach(arguments, function(name) {
+                this.element.className = trim(this.element.className.replace(regExp(name), ' '));
+            }, this);
+        },
+        toggle: function(name) {
+            return this.contains(name) ? (this.remove(name), false) : (this.add(name), true);
+        },
+        contains: function(name) {
+            return regExp(name).test(this.element.className);
+        },
+        item: function(i) {
+            return this.element.className.split(/\s+/)[i] || null;
+        },
+        // bonus
+        replace: function(oldName, newName) {
+            this.remove(oldName), this.add(newName);
+        }
+    };
+
+    // IE8/9, Safari
+    // Remove this if statements to override native classList.
+    if (!('classList' in Element.prototype)) {
+    // Use this if statement to override native classList that does not have for example replace() method.
+    // See browser compatibility: https://developer.mozilla.org/en-US/docs/Web/API/Element/classList#Browser_compatibility.
+    // if (!('classList' in Element.prototype) ||
+    //     !('classList' in Element.prototype && Element.prototype.classList.replace)) {
+        Object.defineProperty(Element.prototype, 'classList', {
+            get: function() {
+                return new ClassList(this);
+            }
+        });
+    }
+
+    // For others replace() support.
+    if (window.DOMTokenList && !DOMTokenList.prototype.replace) {
+        DOMTokenList.prototype.replace = ClassList.prototype.replace;
+    }
+})();
+
+ +

Spezifikationen

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
SpezifikationStatusKommentar
{{SpecName("HTML WHATWG", "dom.html#dom-classlist", "Element.classList")}}{{Spec2("HTML WHATWG")}}Note within the HTML specification related to the {{htmlattrxref("class")}} attribute.
{{SpecName("DOM WHATWG", "#dom-element-classlist", "Element.classList")}}{{Spec2("DOM WHATWG")}}Initial definition
{{SpecName("DOM4", "#dom-element-classlist", "Element.classList")}}{{Spec2("DOM4")}}
+ +

Browserkompatibilität

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support812{{CompatGeckoDesktop(1.9.2)}}10[1]11.505.1
toggle() method's second argument2412{{CompatGeckoDesktop(24)}}{{CompatNo}}[2]157
Multiple arguments for add() & remove()2812{{CompatGeckoDesktop(26)}}{{CompatNo}}157
replace(){{CompatNo}}{{CompatUnknown}}{{CompatGeckoDesktop("49")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support3.012{{CompatGeckoMobile(1.9.2)}}10[1]11.105.0
toggle method's second argument4.412{{CompatGeckoMobile(24)}}{{CompatNo}}[2]{{CompatUnknown}}7.0
multiple arguments for add() & remove()4.412{{CompatUnknown}}{{CompatNo}}{{CompatUnknown}}7.0
replace(){{CompatNo}}{{CompatUnknown}}{{CompatGeckoDesktop("49")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

[1] Not supported for SVG elements.  See a report at Microsoft about that.
+ [2] Internet Explorer never implemented this. See a report at Microsoft about that.

+ +

Siehe auch

+ + diff --git a/files/de/web/api/element/classname/index.html b/files/de/web/api/element/classname/index.html new file mode 100644 index 0000000000..1af7c129f0 --- /dev/null +++ b/files/de/web/api/element/classname/index.html @@ -0,0 +1,128 @@ +--- +title: Element.className +slug: Web/API/Element/className +translation_of: Web/API/Element/className +--- +
{{APIRef("DOM")}}
+ +

Zusammenfassung

+ +

className holt und setzt den Wert des Attributs class eines bestimmten Elements.

+ +

Syntax

+ +
var cName = elementNodeReference.className;
+elementNodeReference.className = cName;
+ + + +

Beispiel

+ +
let elm = document.getElementById('item');
+
+if(elm.className === 'active'){
+    elm.className = 'inactive';
+} else {
+    elm.className = 'active';
+}
+ +

Anmerkungen

+ +

Der Name className wird für diese Eigenschaft anstelle von class benutzt, um Komplikationen mit dem Schlüsselwort "class", welches in vielen Sprachen verwendet wird um das DOM zu verändern, zu vermeiden.

+ +

className kann auch eine Instanz von {{domxref("SVGAnimatedString")}} wenn das element ein {{domxref("SVGElement")}} ist. Es ist besser das Attribut className eines Elements zu ändern, in dem {{domxref("Element.getAttribute")}} verwendet beziehungsweise {{domxref("Element.setAttribute")}}, wenn man mit SVG Elementen arbeitet.

+ +
elm.setAttribute('class', elm.getAttribute('class'))
+ +

 

+ +

Spezifikation

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpezifikationStatusKommentar
{{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")}}Ursprüngliche Definition
+ +

Browserkompabilität

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FunktionalitätChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Grundsätzliche Unterstützung{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FunktionalitätAndroid webviewChrome für AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Grundsätzliche Unterstützung{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

See also

+ + diff --git a/files/de/web/api/element/getboundingclientrect/index.html b/files/de/web/api/element/getboundingclientrect/index.html new file mode 100644 index 0000000000..736314305d --- /dev/null +++ b/files/de/web/api/element/getboundingclientrect/index.html @@ -0,0 +1,62 @@ +--- +title: Element.getBoundingClientRect() +slug: Web/API/Element/getBoundingClientRect +translation_of: Web/API/Element/getBoundingClientRect +--- +
{{APIRef("DOM")}}
+ +

Die Methode Element.getBoundingClientRect()  gibt die Größe eines Elementes und dessen relative Position zum Viewport zurück.

+ +

Syntax

+ +
var domRect = element.getBoundingClientRect();
+
+ +

Rückgabe

+ +

Der zurückgegebene Wert ist ein DOMRect Objekt, welches die Vereinigungsmenge aller von getClientRects() zurückgegebenen Rechtecken eines Elementes darstellt, das heißt, der CSS border-boxes, die mit dem Element verknüpft sind.

+ +

Der Rückgabewert ist das kleinste Rechteck welches das komplette Element beinhaltet. Es enthält die read-only-Eigenschaften left, top, right ,bottom, x, y, width und height, welche die border-box in Pixeln beschreibt. Alle Eigenschaften, abgesehen von width und height, sind realtiv zur linken oberen Ecke des Viewports.

+ +
+

Merke: {{Gecko("1.9.1")}} fügt die Eigenschaften Breite und Höhe zu dem DOMRect Objekt hinzu.

+
+ +

Leere Borderboxen werden vollständig ignoriert. Sind sämtliche Borderboxen eines Elements leer, oder entsprechen die top und left Angaben der Borderbox der ersten CSS-Box (in der Reihenfolge des Inhalts), so wird Null (zero) für top und left zurückgegeben.

+ +

Ein Rechteck mit Breiten- und Höhenwerten von Null wird stattdessen zurückgegeben, und wo top und left den top-left Werten der Border-Box der ersten CSS-Box (in Reihenfolge des Inhaltes) entsprechen.

+ +

Bei der Berechnung des Rechtecks werden sowohl scrollbare Elemente sowie Scrolling an sich (wie viel bereits gescrollt wurde) einbezogen. Das bedeutet, dass die top und left Eigenschaften ihre Werte verändern, sobald sich deren Scrollposition verändert (d.h. ihre Werte sind relativ zum Viewport und nicht absolut).

+ +

Will man die Position des  Rechtecks in Bezug auf die Linke/Obere Ecke des Dokumentes haben, was der absoluten Position des Rechteckes entspricht, muss man zu den top und left Positionen, die Werte von window.scrollX und window.scrollY, addieren.

+ +

Um Browserkompabilität zu gewährleisten, nutzen Sie window.pageXOffset und window.pageYOffset statt window.scrollY und window.scrollX. Sollten window.pageXOffsetwindow.pageYOffsetwindow.scrollX and window.scrollY undefined sein, nutzen Sie (((t = document.documentElement) || (t = document.body.parentNode)) && typeof t.ScrollLeft == 'number' ? t : document.body).ScrollLeft and (((t = document.documentElement) || (t = document.body.parentNode)) && typeof t.ScrollTop == 'number' ? t : document.body).ScrollTop.

+ +

Beispiel

+ +
// rect is a DOMRect object with four properties: left, top, right, bottom
+var rect = obj.getBoundingClientRect();
+
+ +

Browser compatibility

+ +
{{Compat("api.Element.getBoundingClientRect")}}
+ +

Specification

+ + + +

Notes

+ +

getBoundingClientRect() wurde erstmals im DHTML Objektmodell von MS IE implementiert.

+ +

Der Rückgabewert von getBoundingClientRect() ist konstant, es können keine weiteren Eigenschaften hinzugefügt werden.

+ +

See also

+ + diff --git a/files/de/web/api/element/hasattribute/index.html b/files/de/web/api/element/hasattribute/index.html new file mode 100644 index 0000000000..991e9b9dcc --- /dev/null +++ b/files/de/web/api/element/hasattribute/index.html @@ -0,0 +1,129 @@ +--- +title: Element.hasAttribute() +slug: Web/API/Element/hasAttribute +tags: + - API + - Attribut + - DOM + - Element + - Méthode +translation_of: Web/API/Element/hasAttribute +--- +
{{APIRef("DOM")}}
+ +

Die Methode Element.hasAttribute() nimmt einen String als Argument und gibt einen Boolean zurück. Der als Argument übergebene String spezifiziert das gemeinte Attribut und der Rückabe Wert gibt an, ob dieses Attribut in dem jeweiligen Element vorkommt . 

+ +

Syntax

+ +
var result = element.hasAttribute(name);
+
+ +
+
result
+
Rückgabewert, wahr oder falsch.
+
name
+
Ein String, der das jeweilige Attribut spezifiziert.
+
+ +

Beispiel

+ +
var foo = document.getElementById("foo");
+if (foo.hasAttribute("bar")) {
+    // do something
+}
+
+ +

Polyfill

+ +
;(function(prototype) {
+    prototype.hasAttribute = prototype.hasAttribute || function(name) {
+        return !!(this.attributes[name] &&
+                  this.attributes[name].specified);
+    }
+})(Element.prototype);
+
+ +

Notizen

+ +
{{DOMAttributeMethods}}
+ +

Spezifikationen

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpezifikationStatusKommentar
{{SpecName('DOM WHATWG', '#dom-element-hasattribute', 'Element.hasAttribute()')}}{{Spec2('DOM WHATWG')}}Von {{SpecName('DOM3 Core')}}, verlegt von {{domxref("Node")}} nach {{domxref("Element")}}
{{SpecName('DOM3 Core', 'core.html#ID-ElHasAttr', 'Element.hasAttribute()')}}{{Spec2('DOM3 Core')}}Keine Veränderungen zu {{SpecName('DOM2 Core')}}
{{SpecName('DOM2 Core', 'core.html#ID-ElHasAttr', 'Element.hasAttribute()')}}{{Spec2('DOM2 Core')}}Initiale Definition.
+ +

Browser Kompatibilität

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}8.0{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
diff --git a/files/de/web/api/element/index.html b/files/de/web/api/element/index.html new file mode 100644 index 0000000000..71975f163b --- /dev/null +++ b/files/de/web/api/element/index.html @@ -0,0 +1,522 @@ +--- +title: Element +slug: Web/API/Element +tags: + - DOM + - Interface +translation_of: Web/API/Element +--- +

{{ APIRef("DOM") }}

+ +

The Element interface represents an object of a {{domxref("Document")}}. This interface describes methods and properties common to all kinds of elements. Specific behaviors are described in interfaces which inherit from Element but add additional functionality. For example, the {{domxref("HTMLElement")}} interface is the base interface for HTML elements, while the {{domxref("SVGElement")}} interface is the basis for all SVG elements.

+ +

Languages outside the realm of the Web platform, like XUL through the XULElement interface, also implement it.

+ +

Properties

+ +

Inherits properties from its parents {{domxref("Node")}}, and its own parent, {{domxref("EventTarget")}}, and implements those of {{domxref("ParentNode")}}, {{domxref("ChildNode")}}, {{domxref("NonDocumentTypeChildNode")}}, and {{domxref("Animatable")}}.

+ +
+
{{ domxref("Element.attributes") }} {{readOnlyInline}}
+
Returns a {{ domxref("NamedNodeMap") }} that lists all attributes associated with the element.
+
{{ domxref("ParentNode.childElementCount") }}
+
Is a {{jsxref("Number")}} representing the number of child nodes that are elements.
+
{{ domxref("ParentNode.children") }}
+
Is a live {{ domxref("HTMLCollection") }} containing all child elements of the element, as a collection.
+
{{ domxref("Element.classList") }} {{readOnlyInline}}
+
Returns a {{ domxref("DOMTokenList") }} containing the list of class attributes.
+
{{ domxref("Element.className") }}
+
Is a {{domxref("DOMString")}} representing the class of the element.
+
{{ domxref("Element.clientHeight") }} {{experimental_inline}} {{readOnlyInline}}
+
Returns a {{jsxref("Number")}} representing the inner height of the element.
+
{{ domxref("Element.clientLeft") }} {{experimental_inline}} {{readOnlyInline}}
+
Returns a {{jsxref("Number")}} representing the width of the left border of the element.
+
{{ domxref("Element.clientTop") }} {{experimental_inline}} {{readOnlyInline}}
+
Returns a {{jsxref("Number")}} representing the width of the top border of the element.
+
{{ domxref("Element.clientWidth") }} {{experimental_inline}} {{readOnlyInline}}
+
Returns a {{jsxref("Number")}} representing the inner width of the element.
+
{{ domxref("ParentNode.firstElementChild") }}
+
Is a {{ domxref("Element") }}, the first direct child element of an element, or null if the element has no child elements.
+
{{ domxref("Element.id") }}
+
Is a {{domxref("DOMString")}} representing the id of the element.
+
{{ domxref("Element.innerHTML") }} {{experimental_inline}}
+
Is a {{domxref("DOMString")}} representing the markup of the element's content.
+
{{ domxref("ParentNode.lastElementChild") }}
+
Is a {{ domxref("Element") }}, the last direct child element of an element, or null if the element has no child elements.
+
{{ domxref("NonDocumentTypeChildNode.nextElementSibling") }}
+
Is a {{ domxref("Element") }}, the element immediately following the given one in the tree, or null if there's no sibling node.
+
{{ domxref("Element.outerHTML") }} {{experimental_inline}}
+
Is a {{domxref("DOMString")}} representing the markup of the element including its content. When used as a setter, replaces the element with nodes parsed from the given string.
+
{{ domxref("NonDocumentTypeChildNode.previousElementSibling") }}
+
Is a {{ domxref("Element") }}, the element immediately preceding the given one in the tree, or null if there is no sibling element.
+
{{ domxref("Element.scrollHeight") }} {{experimental_inline}} {{readOnlyInline}}
+
Returns a {{jsxref("Number")}} representing the scroll view height of an element.
+
{{ domxref("Element.scrollLeft") }} {{experimental_inline}}
+
Is a {{jsxref("Number")}} representing the left scroll offset of the element.
+
{{ domxref("Element.scrollLeftMax") }} {{non-standard_inline}} {{readOnlyInline}}
+
Returns a {{jsxref("Number")}} representing the maximum left scroll offset possible for the element.
+
{{ domxref("Element.scrollTop") }} {{experimental_inline}}
+
Is a {{jsxref("Number")}} representing the top scroll offset the an element.
+
{{ domxref("Element.scrollTopMax") }} {{non-standard_inline}} {{readOnlyInline}}
+
Returns a{{jsxref("Number")}} representing the maximum top scroll offset possible for the element.
+
{{ domxref("Element.scrollWidth") }} {{experimental_inline}} {{readOnlyInline}}
+
Returns a {{jsxref("Number")}} representing the scroll view width of the element.
+
{{domxref("Element.shadowRoot") }} {{experimental_inline}} {{readOnlyInline}}
+
...
+
{{ domxref("Element.tagName") }} {{readOnlyInline}}
+
Returns a {{domxref("String")}} with the name of the tag for the given element.
+
{{ domxref("Element.undoManager")}} {{experimental_inline}} {{readOnlyInline}}
+
Returns the {{domxref("UndoManager")}} associated with the element.
+
{{ domxref("Element.undoScope")}} {{experimental_inline}}
+
Is a {{jsxref("Boolean")}} indicating if the element is an undo scope host, or not.
+
+ +

Event handlers

+ +
+
{{ domxref("Element.ongotpointercapture") }}
+
+
{{ domxref("Element.onlostpointercapture") }}
+
+
{{ domxref("Element.onwheel") }} {{ non-standard_inline() }}
+
Returns the event handling code for the wheel event.
+
+ +

Methods

+ +

Inherits methods from its parents {{domxref("Node")}}, and its own parent, {{domxref("EventTarget")}}, and implements those of {{domxref("ParentNode")}}, {{domxref("ChildNode")}}, {{domxref("NonDocumentTypeChildNode")}}, and {{domxref("Animatable")}}.

+ +
+
{{ domxref("EventTarget.addEventListener()") }}
+
Registers an event handler to a specific event type on the element.
+
{{ domxref("Element.closest()")}} {{experimental_inline}}
+
Returns the {{domxref("Element")}}, descendant of this element (or this element itself), that is the closest ancestor of the elements selected by the selectors given in parameter.
+
{{ domxref("Element.createShadowRoot()")}} {{experimental_inline}}
+
+
{{ domxref("EventTarget.dispatchEvent()") }}
+
Dispatches an event to this node in the DOM and returns a {{jsxref("Boolean")}} that indicates that at least one handler has not canceled it.
+
{{domxref("Element.find()")}}{{experimental_inline}}
+
...
+
{{domxref("Element.findAll()")}}{{experimental_inline}}
+
...
+
{{domxref("Animatable.getAnimationPlayers()")}} {{experimental_inline}}
+
+
{{ domxref("Element.getAttribute()") }}
+
Retrieves the value of the named attribute from the current node and returns it as an {{jsxref("Object")}}.
+
{{ domxref("Element.getAttributeNS()") }}
+
Retrieves the value of the attribute with the specified name and namespace, from the current node and returns it as an {{jsxref("Object")}}.
+
{{ domxref("Element.getAttributeNode()") }} {{obsolete_inline}}
+
Retrievse the node representation of the named attribute from the current node and returns it as an {{ domxref("Attr") }}.
+
{{ domxref("Element.getAttributeNodeNS()") }} {{obsolete_inline}}
+
Retrieves the node representation of the attribute with the specified name and namespace, from the current node and returns it as an {{ domxref("Attr") }}.
+
{{ domxref("Element.getBoundingClientRect()") }} {{experimental_inline}}
+
...
+
{{ domxref("Element.getClientRects()") }} {{experimental_inline}} TYPE of returnvalue????
+
Returns a collection of rectangles that indicate the bounding rectangles for each line of text in a client.
+
{{domxref("Element.getDestinationInsertionPoints()")}} {{experimental_inline}}
+
+
{{ domxref("Element.getElementsByClassName()") }}
+
Returns a live {{ domxref("HTMLCollection") }} that contains all descendant of the current element that posses the list of classes given in parameter.
+
{{ domxref("Element.getElementsByTagName()") }}
+
Returns a live {{ domxref("HTMLCollection") }} containing all descendant elements, of a particular tag name, from the current element.
+
{{ domxref("Element.getElementsByTagNameNS()") }}
+
Returns a live {{ domxref("HTMLCollection") }} containing all descendant elements, of a particular tag name and namespace, from the current element.
+
{{ domxref("Element.hasAttribute()") }}
+
Returns a {{jsxref("Boolean")}} indicating if the element has the specified attribute or not.
+
{{ domxref("Element.hasAttributeNS()") }}
+
Returns a {{jsxref("Boolean")}} indicating if the element has the specified attribute, in the specified namespace, or not.
+
{{ domxref("Element.insertAdjacentHTML") }} {{experimental_inline}}
+
Parses the text as HTML or XML and inserts the resulting nodes into the tree in the position given.
+
{{ domxref("Element.matches()") }} {{experimental_inline}}
+
Returns a {{jsxref("Boolean")}} indicating whether or not the element would be selected by the specified selector string.
+
{{ domxref("Element.querySelector()") }}
+
Returns {{ domxref("Node") }}...
+
{{ domxref("Element.querySelectorAll") }}
+
Returns a {{ domxref("NodeList") }}...
+
{{ domxref("Element.releasePointerCapture")}} {{experimental_inline}}
+
+
{{domxref("ChildNode.remove()")}}
+
Removes the element from the children list of its parent.
+
{{ domxref("Element.removeAttribute()") }}
+
Removes the named attribute from the current node.
+
{{ domxref("Element.removeAttributeNS()") }}
+
Removes the attribute with the specified name and namespace, from the current node.
+
{{ domxref("Element.removeAttributeNode()") }} {{obsolete_inline}}
+
Removes the node representation of the named attribute from the current node.
+
{{ domxref("EventTarget.removeEventListener()") }}
+
Removes an event listener from the element.
+
{{ domxref("Element.requestFullscreen()") }} {{experimental_inline}}
+
Asynchronously asks the browser to make the element full-screen.
+
{{ domxref("Element.requestPointerLock()")}} {{experimental_inline}}
+
Allows to asynchronously ask for the pointer to be locked on the given element.
+
+ +
+
{{ domxref("Element.scrollIntoView()") }} {{experimental_inline}}
+
Scrolls the page until the element gets into the view.
+
{{ domxref("Element.setAttribute()") }}
+
Sets the value of a named attribute of the current node.
+
{{ domxref("Element.setAttributeNS()") }}
+
Sets the value of the attribute with the specified name and namespace, from the current node.
+
{{ domxref("Element.setAttributeNode()") }} {{obsolete_inline}}
+
Sets the node representation of the named attribute from the current node.
+
{{ domxref("Element.setAttributeNodeNS()") }} {{obsolete_inline}}
+
Setw the node representation of the attribute with the specified name and namespace, from the current node.
+
{{ domxref("Element.setCapture()") }} {{non-standard_inline}}
+
Sets up mouse event capture, redirecting all mouse events to this element.
+
{{domxref("Element.setPointerCapture()")}}
+
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("Web Animations", '', '')}}{{Spec2("Web Animations")}}Added the getAnimationPlayers() method.
{{SpecName('Undo Manager', '', 'Element')}}{{Spec2('Undo Manager')}}Added the undoScope and undoManager properties.
{{SpecName('Pointer Events', '#extensions-to-the-element-interface', 'Element')}}{{Spec2('Pointer Events')}}Added the following event handlers: ongotpointercapture and onlostpointercapture.
+ Added the following methods: setPointerCapture() and releasePointerCapture().
{{SpecName('Selectors API Level 2', '#interface-definitions', 'Element')}}{{Spec2('Selectors API Level 2')}}Added the following methods: matches() (implemented as mozMatchesSelector()), find(), findAll().
{{SpecName('Selectors API Level 1', '#interface-definitions', 'Element')}}{{Spec2('Selectors API Level 1')}}Added the following methods: querySelector() and querySelectorAll().
{{SpecName('Pointer Lock', 'index.html#element-interface', 'Element')}}{{Spec2('Pointer Lock')}}Added the requestPointerLock() method.
{{SpecName('Fullscreen', '#api', 'Element')}}{{Spec2('Fullscreen')}}Added the requestFullscreen() method.
{{SpecName('DOM Parsing', '#extensions-to-the-element-interface', 'Element')}}{{Spec2('DOM Parsing')}}Added the following properties: innerHTML, and outerHTML.
+ Added the following method: insertAdjacentHTML().
{{SpecName('CSSOM View', '#extensions-to-the-element-interface', 'Element')}}{{Spec2('CSSOM View')}}Added the following properties: scrollTop, scrollLeft, scrollWidth, scrollHeight, clientTop, clientLeft, clientWidth, and clientHeight.
+ Added the following methods: getClientRects(), getBoundingClientRect(), and scrollIntoView().
{{SpecName('Element Traversal', '#ecmascript-bindings', 'Element')}}{{Spec2('Element Traversal')}}Added inheritance of the {{domxref("ElementTraversal")}} interface.
{{SpecName('DOM WHATWG', '#interface-element', 'Element')}}{{Spec2('DOM WHATWG')}}Removed the following methods: closest(), setIdAttribute(), setIdAttributeNS(), and setIdAttributeNode().
+ Removed the schemaTypeInfo property.
+ Modified the return value of getElementsByTag() and getElementsByTagNS().
+ Moved hasAttributes() form the Node interface to this one.
{{SpecName('DOM3 Core', 'core.html#ID-745549614', 'Element')}}{{Spec2('DOM3 Core')}}Added the following methods: setIdAttribute(), setIdAttributeNS(), and setIdAttributeNode(). These methods were never implemented and have been removed in later specifications.
+ Added the schemaTypeInfo property. This property was never implemented and has been removed in later specifications.
{{SpecName('DOM2 Core', 'core.html#ID-745549614', 'Element')}}{{Spec2('DOM2 Core')}}The normalize() method has been moved to {{domxref("Node")}}.
{{SpecName('DOM1', 'level-one-core.html#ID-745549614', 'Element')}}{{Spec2('DOM1')}}Initial definition.
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support1.0{{CompatGeckoDesktop("1")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}1.0
children{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.9")}}7.0 with a significant bug [1]
+ 9.0 according to the spec
{{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(), and releasePointerCapture(){{CompatNo}}{{CompatNo}}10.0 {{property_prefix("MS")}}{{CompatNo}}{{CompatNo}}
matches() {{experimental_inline}}{{CompatVersionUnknown}} with the non-standard name webkitMatchesSelector{{CompatGeckoDesktop("1.9.2")}} with the non-standard name mozMatchesSelector
+ {{CompatGeckoDesktop("34")}} with the standard name
9.0 with the non-standard name msMatchesSelector11.5 with the non-standard name oMatchesSelector
+ 15.0 with the non-standard name webkitMatchesSelector
5.0 with the non-standard name webkitMatchesSelector
find() and findAll(){{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
requestPointerLock()16.0 {{property_prefix("webkit")}}, behind an about:flags
+ 22.0 {{property_prefix("webkit")}} (with special cases, progressively lifted see [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")}}
undoManager and undoScope{{CompatNo}}{{CompatVersionUnknown}} (behind the dom.undo_manager.enabled pref){{CompatNo}}{{CompatNo}}{{CompatNo}}
attributes{{CompatUnknown}}{{CompatGeckoDesktop("22")}}
+ Before this it was available via the {{domxref("Node")}} interface that any element inherits.
{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
scrollTopMax() and scrollLeftMax(){{CompatNo}}{{CompatGeckoDesktop("16")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
closest(){{CompatUnknown}}{{CompatGeckoDesktop("35")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
hasAttributes(){{CompatVersionUnknown}}{{CompatGeckoDesktop("1.0")}} (on the {{domxref("Node")}} interface)
+ {{CompatGeckoDesktop("35")}} (on this interface
{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support1.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")}} (on the {{domxref("Node")}} interface)
+ {{CompatGeckoMobile("35")}} (on this interface
{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

[1] Internet Explorer 7 and 8 incorrectly return the comments as part of the children of an Element. This is fixed in Internet Explorer 9 and later.

+ +

[2] Chrome 16 allowed webkitRequestPointerLock() only in fullscreen; Chrome 21 for trusted web site (permission asked); Chrome 22 allowed it by default for all same-origin document; Chrome 23 allowed it in sandboxed {{HTMLElement("iframe")}} if the non-standard value webkit-allow-pointer-lock is set to the {{htmlattrxref("sandbox", "iframe")}} attribute.

diff --git a/files/de/web/api/element/innerhtml/index.html b/files/de/web/api/element/innerhtml/index.html new file mode 100644 index 0000000000..a5d3d3011d --- /dev/null +++ b/files/de/web/api/element/innerhtml/index.html @@ -0,0 +1,204 @@ +--- +title: Element.innerHTML +slug: Web/API/Element/innerHTML +translation_of: Web/API/Element/innerHTML +--- +
{{APIRef("DOM")}}
+ +

Die {{domxref("Element")}} Eigenschaft innerHTML ruft das im Element enthaltene HTML-oder XML-Markup ab oder legt dieses fest.

+ +
Hinweis: Wenn ein {{HTMLElement("div")}}, {{HTMLElement("span")}} oder {{HTMLElement("noembed")}}-Knoten einen untergeordneten Textknoten mit den Zeichen &, < oder > enthält, gibt innerHTML diese Zeichen als ihre entsprechende HTML-Entitäten "&amp;", "&lt;" bzw. "&gt;" zurück. Verwenden Sie {{domxref("Node.textContent")}}, um eine reine Kopie des Inhalts dieser Textknoten zu erhalten.
+ +

Verwenden Sie die Methode {{domxref("Element.insertAdjacentHTML", "insertAdjacentHTML()")}}, um den HTML-Code in das Dokument einzufügen, anstatt den Inhalt eines Elements zu ersetzen.

+ +

Syntax

+ +
const content = element.innerHTML;
+
+element.innerHTML = htmlString;
+
+ +

Wert

+ +

Ein {{domxref("DOMString")}}, das die HTML-Serialisierung der Nachkommen des Elements enthält. Wenn Sie den Wert von innerHTML festlegen, werden alle Nachkommen des Elements entfernt und durch Knoten ersetzt, die durch Analysieren des in htmlString angegebenen HTML-Codes erstellt werden.

+ +

Exceptions

+ +
+
SyntaxError
+
Es wurde versucht, den Wert von innerHTML mit einem nicht ordnungsgemäß formatierten HTML-String festzulegen.
+
NoModificationAllowedError
+
Es wurde versucht, den HTML-Code in einen Knoten einzufügen, dessen übergeordnetes Element {{domxref("Document")}} ist.
+
+ +

Nutzungshinweise

+ +

Die innerHTML-Eigenschaft kann verwendet werden, um den aktuellen HTML-Quellcode der Seite einschließlich aller Änderungen zu überprüfen, die seit dem erstmaligen Laden der Seite vorgenommen wurden.

+ +

HTML-Inhalte eines Elements auslesen

+ +

Das Lesen von innerHTML bewirkt, dass der Benutzer-Agent das HTML- oder XML-Fragment serialisiert, das aus den Nachkommen des Elements besteht. Der resultierende String wird zurückgegeben.

+ +
let contents = myElement.innerHTML;
+ +

Auf diese Weise können Sie das HTML-Markup der Inhaltsknoten des Elements anzeigen.

+ +
+

Hinweis: Das zurückgegebene HTML- oder XML-Fragment wird basierend auf dem aktuellen Inhalt des Elements generiert, sodass das Markup und Formatierung des zurückgegebenen Fragments wahrscheinlich nicht mit dem ursprünglichen Seiten-Markup übereinstimmt.

+
+ +

Inhalte eines Element ersetzen

+ +

Durch das Festlegen des Wertes von innerHTML können Sie den vorhandenen Inhalt eines Elements problemlos durch neuen Inhalt ersetzen.

+ +

Beispielsweise können Sie den gesamten Inhalt eines Dokuments löschen, indem Sie den Inhalt des Attributs {{domxref("Document.body", "body")}} löschen:

+ +
document.body.innerHTML = "";
+ +

In diesem Beispiel wird das aktuelle HTML-Markup des Dokuments abgerufen und die Zeichen "<" durch die HTML-Entität "&lt;" ersetzt, wodurch der HTML-Code im Wesentlichen in unformatierten Text umgewandelt wird. Dieses wird dann in ein Element {{HTMLElement("pre")}} eingeschlossen. Dann wird der Wert von innerHTML in diesen neuen String geändert. Als Ergebnis wird der Dokumentinhalt durch eine Anzeige des gesamten Quellcodes der Seite ersetzt.

+ +
document.documentElement.innerHTML = "<pre>" +
+         document.documentElement.innerHTML.replace(/</g,"&lt;") +
+            "</pre>";
+ +

Unter der Haube

+ +

Was passiert genau, wenn Sie den Wert von innerHTML festlegen? Der Benutzer-Agent führt dabei die folgenden Schritte aus:

+ +
    +
  1. Der angegebene Wert wird als HTML oder XML analysiert (basierend auf dem Dokumenttyp), sodass ein {{domxref("DocumentFragment")}}-Objekt den neuen Satz von DOM-Knoten für die neuen Elemente darstellt.
  2. +
  3. Wenn das Element, dessen Inhalt ersetzt wird, ein {{HTMLElement("template")}}-Element ist, wird das Attribut {{domxref("HTMLTemplateElement.content", "content")}} des Elements <template> durch das neue DocumentFragment ersetzt, welches in Schritt 1 erstellt wurde.
  4. +
  5. Bei allen anderen Elementen wird der Inhalt des Elements durch die Knoten im neuen DocumentFragment ersetzt.
  6. +
+ +

Sicherheitsüberlegungen

+ +

Es ist nicht ungewöhnlich, dass innerHTML zum Einfügen von Text in eine Webseite verwendet wird. Es besteht jedoch die Möglichkeit, dass dies zu einem Angriffsvektor auf einer Website wird, wodurch ein potenzielles Sicherheitsrisiko entsteht.

+ +
const name = "John";
+// angenommen 'el' ist ein HTML DOM Element
+el.innerHTML = name; // in diesem Fall harmlos
+
+// ...
+
+name = "<script>alert('Ich bin John in einem störenden Alert!')</script>";
+el.innerHTML = name; // in diesem Fall harmlos
+ +

Obwohl dies wie ein {{interwiki("wikipedia", "cross-site scripting")}}-Angriff aussieht, ist das Ergebnis harmlos. HTML5 schreibt vor, dass ein mit innerHTML eingefügtes {{HTMLElement("script")}}-Tag nicht ausgeführt werden soll.

+ +

Es gibt jedoch Möglichkeiten, JavaScript auszuführen, ohne {{HTMLElement("script")}}-Elemente zu verwenden. Daher besteht immer ein Sicherheitsrisiko, wenn Sie innerHTML verwenden, um Strings festzulegen, über die Sie keine Kontrolle haben. Zum Beispiel:

+ +
const name = "<img src='x' onerror='alert(1)'>";
+el.innerHTML = name; // zeigt den alert
+ +

Aus diesem Grund wird empfohlen, innerHTML nicht zum Einfügen von reinem Text zu verwenden. Verwenden Sie stattdessen {{domxref("Node.textContent", "textContent")}}. Der übergebene Inhalt wird nicht als HTML-Code analysiert, sondern als reiner Text eingefügt.

+ +
+

Warnung: Wenn Ihr Projekt einer Sicherheitsüberprüfung unterzogen wird, führt die Verwendung von innerHTML höchstwahrscheinlich dazu, dass Ihr Code abgelehnt wird. Wenn Sie beispielsweise innerHTML in einer Browsererweiterung verwenden und die Erweiterung bei addons.mozilla.org einreichen, wird sie den automatisierten Überprüfungsprozess nicht bestehen.

+
+ +

Beispiel

+ +

In diesem Beispiel wird mit innerHTML ein Mechanismus zum Protokollieren von Nachrichten in einem Feld auf einer Webseite erstellt.

+ +

JavaScript

+ +
function log(msg) {
+  var logElem = document.querySelector(".log");
+
+  var time = new Date();
+  var timeStr = time.toLocaleTimeString();
+  logElem.innerHTML += timeStr + ": " + msg + "<br/>";
+}
+
+log("Logging mouse events inside this container...");
+
+ +

Die Funktion log() erstellt die Protokollausgabe, indem sie mithilfe von {{jsxref("Date.toLocaleTimeString", "toLocaleTimeString()")}} die aktuelle Uhrzeit aus einem {{jsxref("Date")}}-Objekt abruft und einen String aus dem Zeitstempel und dem Nachrichtentext erstellt. Dann wird die Nachricht an die Box mit der Klasse "log" angehängt.

+ +

Wir fügen eine zweite Methode hinzu, die Informationen zu auf {{domxref("MouseEvent")}} basierenden Ereignissen protokolliert (z. B. {{event("mousedown")}}, {{event("click")}} und {{event("mouseenter")}}):

+ +
function logEvent(event) {
+  var msg = "Event <strong>" + event.type + "</strong> at <em>" +
+            event.clientX + ", " + event.clientY + "</em>";
+  log(msg);
+}
+ +

Dann verwenden wir dies als Ereignishandler für eine Reihe von Mausereignissen in der Box, die unser Protokoll enthält:

+ +
var boxElem = document.querySelector(".box");
+
+boxElem.addEventListener("mousedown", logEvent);
+boxElem.addEventListener("mouseup", logEvent);
+boxElem.addEventListener("click", logEvent);
+boxElem.addEventListener("mouseenter", logEvent);
+boxElem.addEventListener("mouseleave", logEvent);
+ +

HTML

+ +

Das HTML für unser Beispiel ist denkbar einfach.

+ +
<div class="box">
+  <div><strong>Log:</strong></div>
+  <div class="log"></div>
+</div>
+ +

Das {{HTMLElement("div")}} mit der Klasse "box" ist nur ein Container für Layoutzwecke, der den Inhalt mit einem Rahmen darstellt. Der <div>, dessen Klasse "log" ist, ist der Container für den Protokolltext.

+ +

CSS

+ +

Das folgende CSS formatiert unseren Beispielinhalt.

+ +
.box {
+  width: 600px;
+  height: 300px;
+  border: 1px solid black;
+  padding: 2px 4px;
+  overflow-y: scroll;
+  overflow-x: auto;
+}
+
+.log {
+  margin-top: 8px;
+  font-family: monospace;
+}
+ +

Ergebnis

+ +

Der resultierende Inhalt sieht so aus. Sie können die Ausgabe im Protokoll anzeigen, indem Sie die Maus in das Feld hinein- und herausbewegen, darauf klicken und so weiter.

+ +

{{EmbedLiveSample("Example", 640, 350)}}

+ +

Spezifikation

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM Parsing', '#dom-element-innerhtml', 'Element.innerHTML')}}{{Spec2('DOM Parsing')}}Initiale Definition
+ +

Browserkompatibilität

+ + + +

{{Compat("api.Element.innerHTML")}}

+ +

Siehe auch

+ + diff --git a/files/de/web/api/element/insertadjacenthtml/index.html b/files/de/web/api/element/insertadjacenthtml/index.html new file mode 100644 index 0000000000..14f05ca474 --- /dev/null +++ b/files/de/web/api/element/insertadjacenthtml/index.html @@ -0,0 +1,144 @@ +--- +title: Element.insertAdjacentHTML() +slug: Web/API/Element/insertAdjacentHTML +tags: + - .textContent() + - Geschwindigkeitsvorteil + - HTML einfügen + - Méthode + - Referenz +translation_of: Web/API/Element/insertAdjacentHTML +--- +
{{APIRef("DOM")}}
+ +

Zusammenfassung

+ +

insertAdjacentHTML() interpretiert den angegebenen Text als HTML oder XML und fügt resultierende Knoten an angegebener Position ins DOM ein. Das Zielobjekt wird nicht erneut interpretiert, wodurch darin enthaltene, bereits existierende Elemente nicht beeinträchtigt werden.
+ Eine zusätzlich erforderliche Serialisierung wird vermieden, was einen deutlichen Geschwindigkeitsvorteil gegenüber einer innerHTML Manipulation ergibt.

+ +

Syntax

+ +
element.insertAdjacentHTML(position, text);
+ +

position beschreibt den Einfügepunkt relativ zu einem Element und muss einem der folgenden Schlüsselbegriffe entsprechen:

+ +
+
'beforebegin'
+
Vor dem element selbst.
+
'afterbegin'
+
Innerhalb des element, direkt vor dessen erstem Kind-Objekt. 
+
'beforeend'
+
Innerhalb des element, direkt nach dessen letztem Kind-Objekt.
+
'afterend'
+
Nach dem element selbst.
+
+ +

text ist die Zeichenfolge, die als HTML oder XML interpretiert und in den DOM-Baum eingesetzt wird.

+ +

Verdeutlichung der position Bezeichner

+ +
<!-- beforebegin -->
+<p>
+  <!-- afterbegin -->
+  foo
+  <!-- beforeend -->
+</p>
+<!-- afterend -->
+ +
Hinweis: Die beforebegin und afterend Positionierungen wirken nur, wenn der Knoten innerhalb des DOM-Baums steht und ein Eltern-Element hat. 
+ +

Beispiel

+ +
// <div id="one">one</div>
+var d1 = document.getElementById('one');
+d1.insertAdjacentHTML('afterend', '<div id="two">two</div>');
+
+// Danach sieht die neue Struktur so aus:
+// <div id="one">one</div><div id="two">two</div>
+ +

Anmerkungen

+ +

Sicherheitsaspekte

+ +

Beim Einfügen von HTML in eine Seite sollten keinesfalls unbehandelte Benutzereingaben genutzt werden (siehe 'Escaping'). 

+ +

Für das Einfügen reinen Texts sollte statt insertAdjacentHTML besser node.textContent benutzt werden. Diese Methode interpretiert Parameter nicht als HTML, sondern fügt puren Text ein.

+ +

Spezifikation

+ + + + + + + + + + + + + + + + +
BeschreibungStatusKommentar
{{SpecName('DOM Parsing', '#widl-Element-insertAdjacentHTML-void-DOMString-position-DOMString-text', 'Element.insertAdjacentHTML()')}}{{ Spec2('DOM Parsing') }} 
+ +

Browser Kompatibilität

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
MerkmalChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
grundsätzlich
+ unterstützt
1.0{{ CompatGeckoDesktop("8.0") }}4.07.04.0 (527)
+
+ +
+ + + + + + + + + + + + + + + + + + + +
MerkmalAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
grundsätzlich
+ unterstützt
{{ CompatUnknown() }}{{ CompatGeckoMobile("8.0") }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +

Siehe auch

+ + diff --git a/files/de/web/api/element/queryselector/index.html b/files/de/web/api/element/queryselector/index.html new file mode 100644 index 0000000000..a3cf7d9d89 --- /dev/null +++ b/files/de/web/api/element/queryselector/index.html @@ -0,0 +1,89 @@ +--- +title: Element.querySelector() +slug: Web/API/Element/querySelector +translation_of: Web/API/Element/querySelector +--- +
{{APIRef}}
+ +

Gibt das erste Unterelement des Elements, von dem es aufgerufen wird, zurück, auf das die angegebenen Selektoren zutreffen.

+ +

Syntax

+ +
element = baseElement.querySelector(selectors);
+
+ + + +

Beispiel

+ +

In diesem Beispiel wird das erste style Element aus dem body Element zurückgegeben, das den type text/css oder keinen type hat.

+ +
var el = document.body.querySelector("style[type='text/css'], style:not([type])");
+
+ +

Bemerkungen

+ +

Gibt null zurück, wenn keine Elemente gefunden werden, andernfalls das Element.

+ +

Eine SYNTAX_ERR Ausnahme tritt auf, wenn die angegebenen Selektoren ungültig sind.

+ +

querySelector() wurde in der WebApps API eingeführt.

+ +

Das Argument querySelector muss der CSS Syntax folgen. Siehe {{domxref("document.querySelector")}} für konkrete Beispiele.

+ +

Browserkompatibilität

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
BrowserSupportAnmerkungen
Internet Explorer8Nur CSS 2.1 Selektoren (IE8)
Firefox (Gecko)3.5 (1.9.1) 
Opera10 
Chrome1 
Safari (webkit)3.2 (525.3)webk.it/16587
+ +

Spezifikation

+ + + +

Siehe auch

+ + diff --git a/files/de/web/api/element/queryselectorall/index.html b/files/de/web/api/element/queryselectorall/index.html new file mode 100644 index 0000000000..009a105b89 --- /dev/null +++ b/files/de/web/api/element/queryselectorall/index.html @@ -0,0 +1,206 @@ +--- +title: Element.querySelectorAll() +slug: Web/API/Element/querySelectorAll +tags: + - Méthode + - Referenz +translation_of: Web/API/Element/querySelectorAll +--- +
{{APIRef("DOM")}}
+ +

Summary

+ +

Gibt eine statische NodeList aller Elemente absteigend des Elements, auf welchem querySelectorAll ausgeführt wird, die mit den angegebenen CSS Selektoren übereinstimmen.

+ +

Syntax

+ +
elementList = baseElement.querySelectorAll(selectors);
+
+ +

wobei:

+ +
+
elementList
+
ist statische Node Liste [ NodeList[elements] ] mit element Objekten.
+
baseElement
+
ist ein element Objekt.
+
selectors
+
ist eine Gruppe von Selektoren die mit dem Element im DOM übereinstimmen soll. 
+
+ +

Beispiele

+ +

Dieses Beispiel gibt eine Liste der p Elementen im HTML body zurück:

+ +
let matches = document.body.querySelectorAll('p');
+
+ +

Dieses Beispiel gibt eine Liste der p Unter-Elementen eines Containers, dessen Überobjekt ein div mit der Klasse 'highlighted' ist:

+ +
let el = document.querySelector('#test');    //return an element with id='test'
+let matches = el.querySelectorAll('div.highlighted > p'); // return a NodeList of p wrapped in a div with attribute class "highlighted"
+
+ +

Dieses Beispiel gibt eine Liste der iframe Elementen die ein data Attribut 'src' besitzen:

+ +
let matches = el.querySelectorAll('iframe[data-src]');
+
+ +

Bemerkungen

+ +

If the specified "selectors" are not found inside the DOM of the page, the method queryselectorAll returns an empty NodeList as specified below:

+ +
> let x = document.body.querySelectorAll('.highlighted'); //case: if the class highlighted doesn't exist in any attribute "class" of the DOM the result is
+> [] //empty NodeList
+ +

querySelectorAll() was introduced in the WebApps API.

+ +

The string argument pass to querySelectorAll must follow the CSS syntax. See {{domxref("document.querySelector")}} for a concrete example.

+ +

We could access a single item inside the NodeList in the following way:

+ +
let x = document.body.querySelectorAll('.highlighted');
+x.length; //return the size of x
+x[i_item]; //where i_item has a value between 0 and x.length-1. The operator "[]" return as in an array the element at index "i_item"
+
+ +

We could iterate inside a NodeList with the construct for(....) {...} as in the following code:

+ +
 let x = document.body.querySelectorAll('.highlighted');
+ let index = 0;
+ for( index=0; index < x.length; index++ ) {
+       console.log(x[index]);
+ }
+ +

So in the above way, it is possible to manage and modify the behaviour of the page.

+ +

Quirks

+ +

querySelectorAll() behaves differently than most common JavaScript DOM libraries, which might lead to unexpected results:

+ +
<div class="outer">
+  <div class="select">
+    <div class="inner">
+    </div>
+  </div>
+</div>
+ +
let select = document.querySelector('.select');
+let inner = select.querySelectorAll('.outer .inner');
+inner.length; // 1, not 0!
+
+ +

In this example, when selecting .outer .inner in the context of .select, .inner is still found, even though .outer is not a descendant of the baseElement (.select).
+ querySelectorAll() only verifies that the last element in the selector is within the baseElement.

+ +

The :scope pseudo-class restores the expected behavior, only matching selectors on descendants of the baseElement:

+ +
let select = document.querySelector('.select');
+let inner = select.querySelectorAll(':scope .outer .inner');
+inner.length; // 0
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM4','#dom-parentnode-queryselectorallselectors','querySelectorAll')}}{{Spec2('DOM4')}} 
{{SpecName('Selectors API Level 2','#queryselectorall','querySelectorAll')}}{{Spec2('Selectors API Level 2')}} 
{{SpecName('Selectors API Level 1','#queryselectorall','querySelectorAll')}}{{Spec2('Selectors API Level 1')}} 
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support1{{CompatGeckoDesktop("1.9.1")}}8103.2 (525.3)
:scope pseudo-class{{ CompatVersionUnknown }}32{{CompatNo}}15[1]7.0
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatGeckoMobile("1.9.1")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}
:scope pseudo-class{{ CompatUnknown }}32{{CompatNo}}{{CompatNo}}7.0
+
+ +

[1] Supported in Opera 15+ by enabling the "Enable <style scoped>" or "Enable experimental Web Platform features" flag in chrome://flags.

+ +

See also

+ + diff --git a/files/de/web/api/element/removeattribute/index.html b/files/de/web/api/element/removeattribute/index.html new file mode 100644 index 0000000000..91be13b037 --- /dev/null +++ b/files/de/web/api/element/removeattribute/index.html @@ -0,0 +1,42 @@ +--- +title: Element.removeAttribute() +slug: Web/API/Element/removeAttribute +tags: + - API + - Attribut + - DOM + - Element + - Méthode +translation_of: Web/API/Element/removeAttribute +--- +

{{ APIRef("DOM") }}

+ +

removeAttribute entfernt ein Attribut vom gegebenen Element.

+ +

Syntax

+ +
element.removeAttribute(attrName);
+
+ + + +

Beispiel

+ +
// <div id="div1" align="left" width="200px">
+document.getElementById("div1").removeAttribute("align");
+// now: <div id="div1" width="200px">
+
+ +

Anmerkungen

+ +

Man sollte removeAttribute verwenden, statt den Attributswert auf null zu setzen (mit setAttribute).

+ +

Der Versuch, ein nicht vorhandenes Attribut zu entfernen, wirft keine Exception.

+ +

{{ DOMAttributeMethods() }}

+ +

Spezifikation

+ +

DOM Level 2 Core: removeAttribute (eingeführt in DOM Level 1 Core)

diff --git a/files/de/web/api/element/requestfullscreen/index.html b/files/de/web/api/element/requestfullscreen/index.html new file mode 100644 index 0000000000..01e207e00a --- /dev/null +++ b/files/de/web/api/element/requestfullscreen/index.html @@ -0,0 +1,118 @@ +--- +title: Element.requestFullscreen() +slug: Web/API/Element/requestFullScreen +translation_of: Web/API/Element/requestFullScreen +--- +
{{APIRef("Fullscreen API")}}
+ +

Die Funktion Element.requestFullscreen() sendet eine asynchrone Anfrage, um das Element in Vollbild darzustellen.

+ +

Es ist nicht garantiert, dass das Element in Vollbild angezeigt werden wird. Wenn die Berechtigung dazu erteilt wird, erhält das Dokument ein {{event("fullscreenchange")}} Event, um es wissen zu lassen, dass nun etwas in Vollbild angezeigt wird. Wird die Berechtigung jedoch verweigert, erhält das Dokument ein {{event('fullscreenerror')}} Event.

+ +
+

Nur Elemente im HTML Namespace (Standard HTML Elemente), plus die {{HTMLElement("svg")}} und {{HTMLElement("math")}} Elemente, welche sich im Top-Level Dokument oder in einem {{HTMLElement('iframe')}} mit dem {{htmlattrxref("allowfullscreen", "iframe")}} Attribut befinden, können im Vollbildmodus angezeigt werden. Das bedeutet, dass ein {{HTMLElement('frame')}} oder ein {{HTMLElement('object')}} dies nicht kann.

+
+ +

Syntax

+ +
Element.requestFullscreen();
+
+ +

Beispiel

+ +

Bevor requestFullScreen() aufgerufen wird, sollte man Eventhandler für die {{event("fullscreenchange")}} und {{event("fullscreenerror")}} Events erstellen, damit man erfährt, wenn das Dokument in den Vollbildmodus wechselt (oder die entsprechende Berechtigung dazu fehlt).

+ +

tbd

+ +

Spezifikationen

+ + + + + + + + + + + + + + + + +
SpezifikationStatusKommentar
{{SpecName("Fullscreen", "#dom-element-requestfullscreen", "Element.requestFullScreen()")}}{{Spec2("Fullscreen")}}Ursprüngliche Definition
+ +

Browser-Kompatibilität

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefoxInternet ExplorerEdgeOperaSafari
Grundlegene Unterstütung{{CompatVersionUnknown}}{{property_prefix("webkit")}}[1]{{CompatGeckoDesktop("9.0")}} as mozRequestFullScreen[2]
+ {{CompatGeckoDesktop("47.0")}} (behind full-screen-api.unprefix.enabled
11{{property_prefix("ms")}}[3]{{CompatVersionUnknown}}[3]{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChrome AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Grundlegene Unterstütung{{CompatVersionUnknown}}{{property_prefix("webkit")}}[1]{{CompatVersionUnknown}}{{CompatGeckoMobile("9.0")}} as mozRequestFullScreen[2]
+ {{CompatGeckoMobile("47.0")}} (behind full-screen-api.unprefix.enabled
{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1] Auch implementiert als webkitRequestFullScreen.

+ +

[2] Implementiert als mozRequestFullScreen (man beachte das große S für Screen). Vor Firefox 44 erlaubte Gecko Elementen innerhalb eines {{HTMLElement('frame')}} oder {{HTMLElement('object')}} fälschlicherweise in den Vollbildmodus zu wechseln. Ab Firefox 44 wurde dieses Verhalten behoben: nur Elemente im Top-Level Dokument oder in einem {{HTMLElement('iframe')}} mit dem {{htmlattrxref("allowfullscreen", "iframe")}} Attribut können in den Vollbildmodus wechseln.

+ +

[3] Siehe Dokumentation auf MSDN.

+ +

Siehe auch

+ + diff --git a/files/de/web/api/element/scrollintoview/index.html b/files/de/web/api/element/scrollintoview/index.html new file mode 100644 index 0000000000..ccbcc3e6ea --- /dev/null +++ b/files/de/web/api/element/scrollintoview/index.html @@ -0,0 +1,85 @@ +--- +title: Element.scrollIntoView() +slug: Web/API/Element/scrollIntoView +tags: + - API + - CSSOM Views + - Experimentell + - Methode(2) + - Reference +translation_of: Web/API/Element/scrollIntoView +--- +
{{ APIRef("DOM")}}{{SeeCompatTable}}
+ +

Die Methode Element.scrollIntoView() scrolled das Element in den sichtbaren Bereich des Browsers.

+ +

Syntax

+ +
element.scrollIntoView(); // Gleich mit element.scrollIntoView(true)
+element.scrollIntoView(alignToTop); // Boolean Argument
+element.scrollIntoView(scrollIntoViewOptions); // Object Argument
+
+ +

Parameter

+ +
+
alignToTop
+
Dies ist ein {{jsxref("Boolean")}} Wert: +
    +
  • Bei true wird der obere Rand des Elements an den oberen Rand des sichtbaren Bereichs im Browser gescrolled.
  • +
  • Bei false wird der untere Rand des Elements an den unteren Rand des sichtbaren Bereichs im Browser gescrolled.
  • +
+
+
scrollIntoViewOptions
+
Ein Boolean oder Objekt mit den folgenden Optionen:
+
+
{
+    behavior: "auto"  | "smooth",
+    block:    "start" | "end",
+}
+
+
Wenn der Wert ein Boolean, enspricht true {block: "start"} und false {block: "end"}.
+
+ +

Beispiel

+ +
var element = document.getElementById("box");
+
+element.scrollIntoView();
+element.scrollIntoView(false);
+element.scrollIntoView({block: "end"});
+element.scrollIntoView({block: "end", behavior: "smooth"});
+
+ +

Notizen

+ +

Das Element wird eventuell nicht ganz nach oben oder unten gescrolled. Je nach Layout der anderen Elemente.

+ +

Technische Daten

+ + + + + + + + + + + + + + +
SpecificationStatusKommentar
{{SpecName("CSSOM View", "#dom-element-scrollintoview", "Element.scrollIntoView()")}}{{Spec2("CSSOM View")}}Initial definition
+ +

Browserkompatibilität

+ + + +

{{Compat("api.Element.scrollIntoView")}}

+ +

Siehe auch

+ + diff --git a/files/de/web/api/element/scrollleft/index.html b/files/de/web/api/element/scrollleft/index.html new file mode 100644 index 0000000000..90c28a203e --- /dev/null +++ b/files/de/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") }}

+ +

Die Element.scrollLeft Eigenschaft setzt die Anzahl an Pixel, die der Inhalt eines Elements nach links gescrollt wird, oder liefert diese zurück.

+ +

Beachten Sie:  Wenn die Eigenschaft {{cssxref("direction")}} des Elements den Wert rtl (right-to-left) aufweist,  ist scrollLeft 0, falls der Scrollbalken ganz rechts ist (am Anfang des gescrollten Inhalts),  und nimmt zunehmend negative Werte an, wenn man gegen Ende des Inhalts scrollt.

+ +

Syntax

+ +
// Liefert die Anzahl der gescrollten Pixel
+var sLeft = element.scrollLeft;
+
+ +

sLeft ist ein Integer-Wert, der die Anzahl der Pixel repräsentiert, die element nach links gescrollt ist.

+ +
// Set the number of pixels scrolled
+element.scrollLeft = 10;
+
+ +

scrollLeft kann als Integerwert gesetzt werden. Dabei gilt:

+ + + +

Beispiel

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

Spezifikationen

+ + + + + + + + + + + + + + +
SpezifikationStatusKommentar
{{SpecName('CSSOM View', '#dom-element-scrollleft', 'scrollLeft')}}{{Spec2("CSSOM View")}} 
+ +

Browserkompatibilität

+ +

{{Compat("api.Element.scrollLeft")}}

diff --git a/files/de/web/api/element/scrollwidth/index.html b/files/de/web/api/element/scrollwidth/index.html new file mode 100644 index 0000000000..2968c3ea64 --- /dev/null +++ b/files/de/web/api/element/scrollwidth/index.html @@ -0,0 +1,49 @@ +--- +title: Element.scrollWidth +slug: Web/API/Element/scrollWidth +tags: + - Eigenschaft + - Referenz +translation_of: Web/API/Element/scrollWidth +--- +
{{ APIRef("DOM") }}
+ +

Die schreibgeschützte Eigenschaft Element.scrollWidth liefert entweder die Breite (in Pixeln) des Inhaltes eines Elements oder die Breite des Elementes selbst, je nachdem, welche von beiden größer ist. Ist der Inhalt eines Elementes breiter als sein Inhaltsbereich (z.B. wenn Bildlaufleisten mit eingeblendet werden), dann ist die scrollWidth des Elementes größer als seine clientWidth.

+ +
+

Diese Eigenschaft rundet den Wert zu einem Integer (Ganzzahl). Sollte ein Wert mit Nachkommastellen benötigt werden, verwenden Sie {{ domxref("element.getBoundingClientRect()") }}.

+
+ +

Syntax

+ +
var xScrollWidth = element.scrollWidth;
+ +

xScrollWidth ist die Breite des Inhaltes des Elementes element in Pixeln.

+ +

Beispiel

+ +
<div id="aDiv" style="width: 100px; height: 200px; overflow: auto;">
+  FooBar-FooBar-FooBar
+</div>
+<br>
+<input
+  type="button"
+  value="Show scrollWidth"
+  onclick="alert(document.getElementById('aDiv').scrollWidth);"
+>
+ +

Spezifikation

+ +

Die Eigenschaft scrollWidth ist im CSSOM View Module definiert.

+ +

Referenzen

+ +

{{Compat("api.Element.scrollWidth")}}

+ +

Siehe auch

+ + diff --git a/files/de/web/api/element/setattribute/index.html b/files/de/web/api/element/setattribute/index.html new file mode 100644 index 0000000000..292dd24a6f --- /dev/null +++ b/files/de/web/api/element/setattribute/index.html @@ -0,0 +1,48 @@ +--- +title: Element.setAttribute() +slug: Web/API/Element/setAttribute +tags: + - Attribut + - Methode(2) + - Méthode +translation_of: Web/API/Element/setAttribute +--- +
{{APIRef("DOM")}}
+ +

Fügt dem angegebenen Element ein Attribut hinzu oder ändert den Wert eines vorhandenen Attributs.

+ +

Syntax

+ +
element.setAttribute(name, value);
+
+ + + +

Beispiel

+ +
var d = document.getElementById("d1");
+
+d.setAttribute("align", "center");
+
+ +

Anmerkungen

+ +

Wenn setAttribute auf einem HTML-Element in einem HTML-Dokument aufgerufen wird, wird der Name des Attributes in Kleinbuchstaben umgewandelt.

+ +

Wenn das angegebene Attribut bereits existiert, ersetzt setAttribute den alten Wert. Falls das Attribut nicht existiert, wird es erzeugt.

+ +

Obwohl getAttribute() für fehlende Attribute null liefert, sollte man removeAttribute() statt elt.setAttribute(attr, null) verwenden um ein Attribut zu entfernen.

+ +

setAttribute() zu benutzen, um einige XUL-Attribute (vor allem value) zu ändern, verhält sich inkonsistent, da das Attribut nur den Standardwert spezifiziert. Um den aktuellen Wert zu ändern sollte man die Eigenschaften direkt verwenden. Zum Beispiel elt.value statt elt.setAttribute('value', val).

+ +
{{DOMAttributeMethods}}
+ +

Spezifikation

+ + diff --git a/files/de/web/api/event/bubbles/index.html b/files/de/web/api/event/bubbles/index.html new file mode 100644 index 0000000000..286bac6a23 --- /dev/null +++ b/files/de/web/api/event/bubbles/index.html @@ -0,0 +1,59 @@ +--- +title: Event.bubbles +slug: Web/API/Event/bubbles +translation_of: Web/API/Event/bubbles +--- +

{{ ApiRef("DOM") }}

+ +

Zusammenfassung

+ +

Gibt an, ob ein Event in der DOM-Hierarchie nach oben propagiert wird oder nicht.

+ +

Syntax

+ +
event.bubbles
+ +

Wert

+ +

Ein {{domxref("Boolean")}}, welches true ist, falls das Event durch die DOM-Hierarchie nach oben propagiert wird.

+ +

Beispiel

+ +
 function goInput(e) {
+  // checks bubbles and
+  if (!e.bubbles) {
+     // passes event along if it's not
+     passItOn(e);
+  }
+  // already bubbling
+  doOutput(e)
+}
+
+ +
+

Hinweis: Nur bestimmte Events können weiter nach oben propagiert werden. Die Events, die dazu in der Lage sind, haben den Wert true,  für die hier beschriebene Eigenschaft.

+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG', '#dom-event-bubbles', 'Event.bubbles')}}{{ Spec2('DOM WHATWG') }} 
{{SpecName('DOM2 Events', '#Events-Event-canBubble', 'Event.bubbles')}}{{ Spec2('DOM2 Events') }}Initial definition.
diff --git a/files/de/web/api/event/event/index.html b/files/de/web/api/event/event/index.html new file mode 100644 index 0000000000..ee30a2064c --- /dev/null +++ b/files/de/web/api/event/event/index.html @@ -0,0 +1,72 @@ +--- +title: Event() +slug: Web/API/Event/Event +translation_of: Web/API/Event/Event +--- +

{{APIRef("DOM")}}

+ +

Der Konstruktor: Event()  erstellt ein neues {{domxref("Event")}}.

+ +

Syntax

+ +
 event = new Event(typeArg, eventInit);
+ +

Values

+ +
+
typeArg
+
ist ein {{domxref("DOMString")}} und bestimmt den Namen des Events.
+
eventInit {{optional_inline}}
+
+ +
+
ist ein {{jsxref("Object")}} und beinhaltet folgende Felder: +
    +
  • "bubbles": (Optional) Ein {{jsxref("Boolean")}}, welcher angibt, ob das Event gebubbled werden soll. Der Standardwert ist false.
  • +
  • "cancelable": (Optional) Ein {{jsxref("Boolean")}}, welcher angibt, ob das Event abgebrochen werden kann. Der Standardwert false.
  • +
  • "composed": (Optional) Ein {{jsxref("Boolean")}}, welcher angibt, ob das Event auch außerhalb eines Shadow-Root-Elements empfangen werden kann. Der Standardwert ist false. 
  • +
+
+
+ +

Example

+ +
// create a look event that bubbles up and cannot be canceled
+
+var evt = new Event("look", {"bubbles":true, "cancelable":false});
+document.dispatchEvent(evt);
+
+// event can be dispached from any elmement, not only the document
+myDiv.dispatchEvent(evt);
+
+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG','#interface-event','Event()')}}{{Spec2('DOM WHATWG')}}Initial definition.
+ +

Browser compatibility

+ + + +

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

+ +

See also

+ + diff --git a/files/de/web/api/event/index.html b/files/de/web/api/event/index.html new file mode 100644 index 0000000000..0962ba6de2 --- /dev/null +++ b/files/de/web/api/event/index.html @@ -0,0 +1,253 @@ +--- +title: Event +slug: Web/API/Event +tags: + - API + - DOM + - Event + - Interface + - NeedsTranslation + - Reference + - TopicStub + - UI +translation_of: Web/API/Event +--- +

{{APIRef("DOM")}}

+ +

Das Event Interface repräsentiert jegliches Ereignis, das im DOM auftritt.

+ +

Ein Ereignis kann durch Benutzerinteraktion ausgelöst werden, z.B das Klicken einer Maustaste oder Eingaben der Tastatur, oder durch eine API generiert werden um den Fortschritt eines asynchronen Prozesses zu repräsentieren. Es kann auch durch ein Programm ausgelöst werden, beispielsweise indem die HTMLElement.click() Method eines Elements aufgerufen wird, oder indem ein Ereignis definiert wird und es danach mithilfe von EventTarget.dispatchEvent() an ein Ziel versandt wird.

+ +

Es gibt eine Vielzahl verschiedener Typen von Ereignissen, von denen manche erweiterte Schnittstellen basieren auf dem zentralen Event Interface benutzen. Event beinhaltet alle Attribute und Methoden, die allen Ereignissen gemein sind.

+ +

Viele DOM-Element können für das Empfangen dieser Events konfiguriert werden und rufen Code auf, um sie zu behandeln. Event-Handler werden normalerweise mit unterschiedlichen HTML-Elementen (so wie <button>, <div>, <span>, etc.) verbunden, durch den Aufruf von EventTarget.addEventListener(). Dies ersetzt größtenteils die alten HTML Event Handler Attribute. Die neueren Event-Handler können außerdem nötigenfalls mithilfe von removeEventListener() wieder entfernt werden.

+ +
+

Note: Ein Element kann mehrere solcher Handler besitzen, sogar für das selbe Ereignis—so können sie verschiedene, unabhängige Code-Module angebracht werden, jeweils für deren unabhängige Zwecke. (Zum Beispiel eine Webseite mit einem Werbemodul und einem Statistikmodel, die beide Videowiedergabe überwachen.)

+
+ +

Gitb es viele verschachtelte Element, jedes mit eigenen Event-Handlern, kann das Verarbeiten von Ereignissen siehr schnell komplex werden—im Speziellen wenn ein Elternelement die selben Ereignissen wie sein Kindelement empfängt, weil sie sich überlappen und so Ereignisse technisch gesehen in beiden geschehen. Die Behandlungsreihenfolge solcher Ereignisse hängen von Event bubbling and capture Konfigurationen jedes ausgelösten Event-Handlers ab.

+ +

Interfaces based on Event

+ +

Below is a list of interfaces which are based on the main Event interface, with links to their respective documentation in the MDN API reference. Note that all event interfaces have names which end in "Event".

+ +
+ +
+ +

Constructor

+ +
+
{{domxref("Event.Event", "Event()")}}
+
Creates an Event object, returning it to the caller.
+
+ +

Properties

+ +
+
{{domxref("Event.bubbles")}} {{readonlyinline}}
+
A Boolean indicating whether the event bubbles up through the DOM or not.
+
{{domxref("Event.cancelBubble")}}
+
A historical alias to {{domxref("Event.stopPropagation()")}}. Setting its value to true before returning from an event handler prevents propagation of the event.
+
{{domxref("Event.cancelable")}} {{readonlyinline}}
+
A Boolean indicating whether the event is cancelable.
+
{{domxref("Event.composed")}} {{ReadOnlyInline}}
+
A Boolean value indicating whether or not the event can bubble across the boundary between the shadow DOM and the regular DOM.
+
{{domxref("Event.currentTarget")}} {{readonlyinline}}
+
A reference to the currently registered target for the event. This is the object to which the event is currently slated to be sent; it's possible this has been changed along the way through retargeting.
+
{{domxref("Event.deepPath")}} {{non-standard_inline}}
+
An {{jsxref("Array")}} of DOM {{domxref("Node")}}s through which the event has bubbled.
+
{{domxref("Event.defaultPrevented")}} {{readonlyinline}}
+
Indicates whether or not {{domxref("event.preventDefault()")}} has been called on the event.
+
{{domxref("Event.eventPhase")}} {{readonlyinline}}
+
Indicates which phase of the event flow is being processed.
+
{{domxref("Event.explicitOriginalTarget")}} {{non-standard_inline}} {{readonlyinline}}
+
The explicit original target of the event (Mozilla-specific).
+
{{domxref("Event.originalTarget")}} {{non-standard_inline}} {{readonlyinline}}
+
The original target of the event, before any retargetings (Mozilla-specific).
+
{{domxref("Event.returnValue")}} {{non-standard_inline}}
+
A non-standard alternative (from old versions of Microsoft Internet Explorer) to {{domxref("Event.preventDefault()")}} and {{domxref("Event.defaultPrevented")}}.
+
{{domxref("Event.scoped")}} {{readonlyinline}} {{obsolete_inline}}
+
A {{jsxref("Boolean")}} indicating whether the given event will bubble across through the shadow root into the standard DOM. This property has been renamed to {{domxref("Event.composed", "composed")}}.
+
{{domxref("Event.srcElement")}} {{non-standard_inline}}
+
A non-standard alias (from old versions of Microsoft Internet Explorer) for {{domxref("Event.target")}}.
+
{{domxref("Event.target")}} {{readonlyinline}}
+
A reference to the target to which the event was originally dispatched.
+
{{domxref("Event.timeStamp")}} {{readonlyinline}}
+
The time at which the event was created, in milliseconds. By specification, this value is time since epoch, but in reality browsers' definitions vary; in addition, work is underway to change this to be a {{domxref("DOMHighResTimeStamp")}} instead.
+
{{domxref("Event.type")}} {{readonlyinline}}
+
The name of the event (case-insensitive).
+
{{domxref("Event.isTrusted")}} {{readonlyinline}}
+
Indicates whether or not the event was initiated by the browser (after a user click for instance) or by a script (using an event creation method, like event.initEvent)
+
+ +

Methods

+ +
+
{{domxref("Event.initEvent()")}} {{deprecated_inline}}
+
Initializes the value of an Event created. If the event has already being dispatched, this method does nothing.
+
{{domxref("Event.preventBubble()")}} {{non-standard_inline}} {{Obsolete_inline(24)}}
+
Prevents the event from bubbling. Obsolete, use {{domxref("event.stopPropagation")}} instead.
+
{{domxref("Event.preventCapture()")}} {{non-standard_inline}} {{Obsolete_inline(24)}}
+
Obsolete, use {{domxref("event.stopPropagation")}} instead.
+
{{domxref("Event.preventDefault()")}}
+
Cancels the event (if it is cancelable).
+
{{domxref("Event.stopImmediatePropagation()")}}
+
For this particular event, no other listener will be called. Neither those attached on the same element, nor those attached on elements which will be traversed later (in capture phase, for instance)
+
{{domxref("Event.stopPropagation()")}}
+
Stops the propagation of events further along in the DOM.
+
{{domxref("Event.getPreventDefault()")}} {{non-standard_inline}}
+
Non-standard. Returns the value of {{domxref("Event.defaultPrevented")}}. Use {{domxref("Event.defaultPrevented")}} instead.
+
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG', '#interface-event', 'Event')}}{{Spec2('DOM WHATWG')}}
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
cancelBubble defined on Event{{CompatUnknown}}{{CompatGeckoDesktop(53)}}[1]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
cancelBubble defined on Event{{CompatUnknown}}{{CompatGeckoMobile(53)}}[1]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1] Previous to Firefox 52, this property was defined on the {{domxref("UIEvent")}} interface. See {{bug(1298970)}} for more details.

+ +

See also

+ + diff --git a/files/de/web/api/eventlistener/index.html b/files/de/web/api/eventlistener/index.html new file mode 100644 index 0000000000..c7eb012670 --- /dev/null +++ b/files/de/web/api/eventlistener/index.html @@ -0,0 +1,48 @@ +--- +title: EventListener +slug: Web/API/EventListener +tags: + - API + - DOM + - DOM Events +translation_of: Web/API/EventListener +--- +

{{APIRef("DOM Events")}}

+ +

Methodenübersicht

+ + + + + + + +
void handleEvent (in Event event);
+ +

Methoden

+ +

handleEvent()

+ +

Diese Methode wird immer aufgerufen, wenn ein Event auftritt, welche im EventListener Interface registriert wurden.

+ +
void handleEvent(
+  in Event event
+);
+
+ +
Parameter
+ +
+
event
+
Das DOM-{{ domxref("Event") }} das zu registrieren ist.
+
+ +

Anmerkungen

+ +

Da das Interface mit dem [function] Flag gekennzeichnet ist, implementieren alle JavaScript-Funktionen dieses automatisch. Das Aufrufen von {{ manch("handleEvent") }} einer solchen Implementierung ruft automatisch diese Funktion auf.

+ +

Siehe auch

+ + diff --git a/files/de/web/api/eventsource/index.html b/files/de/web/api/eventsource/index.html new file mode 100644 index 0000000000..7942b2df95 --- /dev/null +++ b/files/de/web/api/eventsource/index.html @@ -0,0 +1,126 @@ +--- +title: EventSource +slug: Web/API/EventSource +tags: + - API + - Interface + - Referenz + - Server-sent events +translation_of: Web/API/EventSource +--- +

{{APIRef("Websockets API")}}

+ +

Das EventSource-Interface erlaubt das Empfangen von Server-Sent Events. Es erlaubt den Zugriff auf Events im text/event-stream Format über eine persistente HTTP-Verbindung.

+ +
+
+ +

Properties

+ +

Diese Interface erbt weitere Properties von seinem Parent-Object {{domxref("EventTarget")}}.

+ +
+
{{domxref("EventSource.onerror")}}
+
Ist eine {{domxref("EventHandler")}}-Instanz. Diese wird aufgerufen, wenn ein Fehler auftritt und das {{event("error")}}-Event auf diesem Object ausgelöst wird.
+
{{domxref("EventSource.onmessage")}}
+
Ist eine {{domxref("EventHandler")}}-Instanz. Diese wir aufgerufen, wenn ein {{event("message")}}-event empfangen wird. Dies ist immer dann der Fall, wenn die Event-Quelle eine neue Nachricht erzeugt hat.
+
{{domxref("EventSource.onopen")}}
+
Ist eine {{domxref("EventHandler")}}-Instanz. Diese wird immer dann aufgerufen, wenn die Verbindung geöffnet wurde, also ein {{event("open")}}-Event empfangen wurde.
+
{{domxref("EventSource.readyState")}} {{readonlyinline}}
+
Ein unsigned short, welcher den aktuellen Status der Verbindung repräsentiert. Gültige werte sind CONNECTING (0), OPEN (1), or CLOSED (2).
+
{{domxref("EventSource.url")}} {{readonlyinline}}
+
Ein {{domxref("DOMString")}}, welcher die URL der Event-Quelle beinhaltet.
+
+ +

Methods

+ +

Diese Interface erbt weitere Methoden von seinem Parent-Object {{domxref("EventTarget")}}.

+ +
+
{{domxref("EventSource.close()")}}
+
Schließt die Verbindung, soweit geöffnet, und setzt den Status (readyState) auf CLOSED. Auf bereits geschlossenen Verbindungen hat diese Methode keinen Effekt.
+
+ +

Spezifikationen

+ + + + + + + + + + + + + + +
SpezifikationStatusKommentar
{{SpecName('HTML WHATWG', "comms.html#the-eventsource-interface", "EventSource")}}{{Spec2('HTML WHATWG')}}
+ + + +

Browser Kompatiblität

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basis-Support9{{ CompatGeckoDesktop("6.0") }}{{CompatUnknown}}115
CORS-Support26{{ CompatGeckoDesktop("11.0") }}{{CompatUnknown}}12{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basis-Support{{ CompatAndroid("4.4") }}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

Siehe auch

+ + diff --git a/files/de/web/api/eventtarget/index.html b/files/de/web/api/eventtarget/index.html new file mode 100644 index 0000000000..3ed264119e --- /dev/null +++ b/files/de/web/api/eventtarget/index.html @@ -0,0 +1,174 @@ +--- +title: EventTarget +slug: Web/API/EventTarget +tags: + - API + - DOM + - DOM Events + - Interface + - NeedsTranslation + - TopicStub +translation_of: Web/API/EventTarget +--- +

{{ApiRef("DOM Events")}}

+ +

EventTarget is an interface implemented by objects that can receive events and may have listeners for them.

+ +

{{domxref("Element")}}, {{domxref("document")}}, and {{domxref("window")}} are the most common event targets, but other objects can be event targets too, for example {{domxref("XMLHttpRequest")}}, {{domxref("AudioNode")}}, {{domxref("AudioContext")}}, and others.

+ +

Many event targets (including elements, documents, and windows) also support setting event handlers via on... properties and attributes.

+ +

Methods

+ +
+
{{domxref("EventTarget.addEventListener()")}}
+
Register an event handler of a specific event type on the EventTarget.
+
{{domxref("EventTarget.removeEventListener()")}}
+
Removes an event listener from the EventTarget.
+
{{domxref("EventTarget.dispatchEvent()")}}
+
Dispatch an event to this EventTarget.
+
+ +

Additional methods for Mozilla chrome code

+ +

Mozilla extensions for use by JS-implemented event targets to implement on* properties. See also WebIDL bindings.

+ + + +

Example:

+ +

Simple implementation of EventTarget

+ +
var EventTarget = function() {
+  this.listeners = {};
+};
+
+EventTarget.prototype.listeners = null;
+EventTarget.prototype.addEventListener = function(type, callback) {
+  if (!(type in this.listeners)) {
+    this.listeners[type] = [];
+  }
+  this.listeners[type].push(callback);
+};
+
+EventTarget.prototype.removeEventListener = function(type, callback) {
+  if (!(type in this.listeners)) {
+    return;
+  }
+  var stack = this.listeners[type];
+  for (var i = 0, l = stack.length; i < l; i++) {
+    if (stack[i] === callback){
+      stack.splice(i, 1);
+      return;
+    }
+  }
+};
+
+EventTarget.prototype.dispatchEvent = function(event) {
+  if (!(event.type in this.listeners)) {
+    return true;
+  }
+  var stack = this.listeners[event.type];
+  event.target = this;
+  for (var i = 0, l = stack.length; i < l; i++) {
+    stack[i].call(this, event);
+  }
+  return !event.defaultPrevented;
+};
+
+ +

{{ EmbedLiveSample('_Simple_implementation_of_EventTarget') }}

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG', '#interface-eventtarget', 'EventTarget')}}{{Spec2('DOM WHATWG')}}No change.
{{SpecName('DOM3 Events', 'DOM3-Events.html#interface-EventTarget', 'EventTarget')}}{{Spec2('DOM3 Events')}}A few parameters are now optional (listener), or accepts the null value (useCapture).
{{SpecName('DOM2 Events', 'events.html#Events-EventTarget', 'EventTarget')}}{{Spec2('DOM2 Events')}}Initial definition.
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support1.0{{CompatVersionUnknown}}{{CompatGeckoDesktop("1")}}9.071.0[1]
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support1.0{{CompatVersionUnknown}}{{CompatGeckoMobile("1")}}9.06.01.0
+
+ +

[1] window.EventTarget does not exist.

+ +

See Also

+ + diff --git a/files/de/web/api/federatedcredential/index.html b/files/de/web/api/federatedcredential/index.html new file mode 100644 index 0000000000..1d7569e449 --- /dev/null +++ b/files/de/web/api/federatedcredential/index.html @@ -0,0 +1,125 @@ +--- +title: FederatedCredential +slug: Web/API/FederatedCredential +tags: + - API + - Föderierte Zugangsdaten + - Schnittstelle + - Zugangsdaten +translation_of: Web/API/FederatedCredential +--- +

{{SeeCompatTable}}{{APIRef("Credential Management API")}}

+ +

Die FederatedCredential Schnittstelle der Credential Management API stellt Informationen über Zugangsdaten eines Anbieters föderierter Identitäten bereit. Ein Anbieter föderierter Identitäten ist ein Gebilde, dem eine Webseite vertraut, eine Nutzerin korrekt zu identifizieren und eine API für diesen Zweck bereit stellt. OpenID Connect ist ein Beispiel für ein Framework für Anbieter föderierter Identitäten.

+ +

In Brwosern, die dies unterstützen, kann eine Instanz dieser Schnittstelle in der credential Funktions des init Objekt für globales {{domxref('fetch')}} mitgegeben werden.

+ +
+
{{domxref("FederatedCredential.FederatedCredential()","FederatedCredential()")}}
+
Erstellt ein neues FederatedCredential Objekt.
+
+ +

Eigenschaften

+ +

Erbt Eigenschaften von seinem Vorfahren, {{domxref("Credential")}}.

+ +
+
{{domxref("FederatedCredential.provider")}} {{readonlyInline}}
+
Gibt einen {{domxref("USVString")}} zurück, der den Anbieter föderierter Identitäten eines Satzes von Zugangsdaten enthält.
+
+ +

Event-Handler

+ +

Keine.

+ +

Methoden

+ +

Keine.

+ +

Beispiele

+ +
var cred = new FederatedCredential({
+  id: id,
+  name: name,
+  provider: 'https://account.google.com',
+  iconURL: iconUrl
+});
+
+// Store it
+navigator.credentials.store(cred)
+  .then(function() {
+  // Mach etwas anderes.
+});
+ +

Spezifikationen

+ + + + + + + + + + + + + + +
SpezifikationStatusKommentar
{{SpecName('Credential Management')}}{{Spec2('Credential Management')}}Initiale Definition.
+ +

Browserkompabilität

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Grundlegende Unterstützung +

{{CompatChrome(51.0)}}

+
{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroid WebviewChrome for AndroidFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari Mobile
Grundlegende Unterstützung{{CompatChrome(51.0)}}{{CompatChrome(51.0)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
diff --git a/files/de/web/api/fetch_api/index.html b/files/de/web/api/fetch_api/index.html new file mode 100644 index 0000000000..d45285bcd1 --- /dev/null +++ b/files/de/web/api/fetch_api/index.html @@ -0,0 +1,84 @@ +--- +title: Fetch API +slug: Web/API/Fetch_API +translation_of: Web/API/Fetch_API +--- +
{{DefaultAPISidebar("Fetch API")}}
+ +

Die Fetch API bietet eine Schnittstelle zum Abrufen von Ressourcen (auch über das Netzwerk). Wer schon einmal mit {{DOMxRef("XMLHttpRequest")}} gearbeitet hat wird Ähnlichkeiten erkennen. Die neue API bietet jedoch einen ganzen Satz leistungsfähigerer und flexiblerer Funktionen.

+ +

Konzepte und Verwendung

+ +

Fetch bietet eine generische Definition von {{DOMxRef("Request")}} und {{DOMxRef("Response")}} Objekten (und anderen Dingen, die mit Anfragen über ein Netzwerk zu tun haben). Dadurch können sie überall dort eingesetzt werden, wo sie in Zukunft benötigt werden, sei es für Service Worker, die Cache-API und andere ähnliche Dinge, mit denen Anfragen und Antworten abgewickelt oder geändert werden, oder in jedem Anwendungsfall, für den Sie möglicherweise eigene Antworten programmatisch erstellen müssen.

+ +

Sie enthält auch eine Definition für verwandte Konzepte wie CORS und die HTTP-Origin-Semantik, die ihre separaten Definitionen an anderer Stelle ersetzen.

+ +

Verwenden Sie zum Erstellen einer Anfrage und zum Abrufen einer Ressource die Methode {{DOMxRef("WindowOrWorkerGlobalScope.fetch()")}}. Es ist in mehreren Schnittstellen implementiert, insbesondere {{DOMxRef("Window")}} und {{DOMxRef("WorkerGlobalScope")}}. Dadurch ist es in nahezu jedem Kontext verfügbar, in dem Sie Ressourcen abrufen möchten.

+ +

Die Methode fetch() nimmt ein obligatorisches Argument entgegen, den Pfad zu der Ressource, die Sie abrufen möchten. Sie gibt ein {{DOMxRef("Promise")}} zurück, das in die {{DOMxRef("Response")}} dieser Anfrage aufgelöst wird, unabhängig davon, ob sie erfolgreich ist oder nicht. Sie können optional auch ein init Objekt mit Optionen als zweites Argument übergeben (siehe {{DOMxRef("Request")}}).

+ +

Nachdem eine {{DOMxRef("Response")}} abgerufen wurde, stehen eine Reihe von Methoden zur Verfügung, mit denen der Antwort-Inhalt (Body) definiert werden kann und wie er verarbeitet werden soll (siehe {{DOMxRef("Body")}}).

+ +

Sie können eine Anfrage und Antwort direkt erstellen, indem Sie die Konstruktoren {{DOMxRef("Request.Request", "Request()")}} und {{DOMxRef("Response.Response", "Response()")}} verwenden, was Sie aber wahrscheinlich in den seltensten Fällen tun werden. Stattdessen werden diese eher als Ergebnis anderer API-Aktionen erstellt (z. B. durch {{DOMxRef("FetchEvent.respondWith()")}} von Service Workern).

+ +
+

Hinweis: Erfahren Sie mehr über die Verwendung der Funktionen der Fetch API in der Verwendung von Fetch und lernen Sie die Grundkonzepte von Fetch.

+
+ +

Einen Abruf abbrechen

+ +

Browser haben begonnen, experimentelle Unterstützung für die Schnittstellen {{DOMxRef("AbortController")}} und {{DOMxRef("AbortSignal")}} hinzuzufügen (auch Abort API genannt), die den Abbruch von Operationen durch Fetch und XHR ermöglichen, sofern diese noch nicht abgeschlossen sind. Weitere Informationen finden Sie auf den Schnittstellenseiten.

+ +

Fetch Interfaces

+ +
+
{{DOMxRef("WindowOrWorkerGlobalScope.fetch()")}}
+
Die fetch() Methode zum Abrufen einer Ressource.
+
{{DOMxRef("Headers")}}
+
Stellt die Antwort-/Anfrageheader dar, damit Sie sie abfragen und je nach Ergebnis unterschiedliche Aktionen ausführen können.
+
{{DOMxRef("Request")}}
+
Stellt eine Ressourcenanfrage dar.
+
{{DOMxRef("Response")}}
+
Stellt die Antwort auf eine Anfrage dar.
+
+ +

Fetch mixin

+ +
+
{{DOMxRef("Body")}}
+
Stellt Methoden bereit, die sich auf den Hauptteil (Body) der Antwort/Anfrage beziehen, sodass Sie den Inhaltstyp angeben können und wie dieser behandelt werden soll.
+
+ +

Spezifikationen

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("Fetch")}}{{Spec2("Fetch")}}Initial definition
+ +

Browserkompatibilität

+ + + +

{{Compat("api.WindowOrWorkerGlobalScope.fetch")}}

+ +

Siehe auch

+ + diff --git a/files/de/web/api/file/filename/index.html b/files/de/web/api/file/filename/index.html new file mode 100644 index 0000000000..7dbf4f7559 --- /dev/null +++ b/files/de/web/api/file/filename/index.html @@ -0,0 +1,35 @@ +--- +title: File.fileName +slug: Web/API/File/fileName +tags: + - DOM + - Files +translation_of: Web/API/File/fileName +--- +

{{APIRef("File API")}}{{non-standard_header}}

+ +

{{deprecated_header(7.0)}}

+ +

Summary

+ +

Returns the name of the file. For security reasons the path is excluded from this property.

+ +
This property is deprecated. Use {{domxref("File.name")}} instead.
+ +

Syntax

+ +
var name = instanceOfFile.fileName
+ +

Value

+ +

A string

+ +

Specification

+ +

Not part of any specification.

+ +

See also

+ + diff --git a/files/de/web/api/file/filesize/index.html b/files/de/web/api/file/filesize/index.html new file mode 100644 index 0000000000..0c91c5f739 --- /dev/null +++ b/files/de/web/api/file/filesize/index.html @@ -0,0 +1,36 @@ +--- +title: File.fileSize +slug: Web/API/File/fileSize +tags: + - DOM + - Files + - Property +translation_of: Web/API/File/fileSize +--- +

{{APIRef("File API") }}{{non-standard_header}}

+ +

{{deprecated_header(7.0)}}

+ +

Summary

+ +

Returns the size of a file in bytes.

+ +
This property is deprecated. Use {{domxref("Blob.size")}} instead.
+ +

Syntaxe

+ +
var size = instanceOfFile.fileSize
+ +

Value

+ +

A number

+ +

Specification

+ +

Not part of any specification.

+ +

See also

+ + diff --git a/files/de/web/api/file/getastext/index.html b/files/de/web/api/file/getastext/index.html new file mode 100644 index 0000000000..fefda6647a --- /dev/null +++ b/files/de/web/api/file/getastext/index.html @@ -0,0 +1,78 @@ +--- +title: File.getAsText() +slug: Web/API/File/getAsText +tags: + - DOM + - Files +translation_of: Web/API/File/getAsText +--- +

{{APIRef("File API") }}{{non-standard_header}}

+ +

{{deprecated_header(7.0)}}

+ +

Summary

+ +

The getAsText method provides the file's data interpreted as text using a given encoding.

+ +
+

Note: This method is obsolete; you should use the {{domxref("FileReader")}} method {{domxref("FileReader.readAsText()","readAsText()")}} instead.

+
+ +

Syntaxe

+ +
var str = instanceOfFile.getAsText(encoding);
+ +

Parameters

+ +
+
encoding
+
A string indicating the encoding to use for the returned data. If this string is empty, UTF-8 is assumed.
+
+ +

Returns

+ +

A string containing the file's data interpreted as text in the specified encoding.

+ +

Example

+ +
// fileInput is a HTMLInputElement: 
+var fileInput = document.getElementById("myfileinput");
+
+// files is a FileList object (similar to NodeList)
+var files = fileInput.files;
+
+// object for allowed media types
+var accept = {
+  binary : ["image/png", "image/jpeg"],
+  text   : ["text/plain", "text/css", "application/xml", "text/html"]
+};
+
+var file;
+
+for (var i = 0; i < files.length; i++) {
+  file = files[i];
+
+  // if file type could be detected
+  if (file !== null) {
+    if (accept.text.indexOf(file.mediaType) > -1) {
+      // file is of type text, which we accept
+      // make sure it's encoded as utf-8
+      var data = file.getAsText("utf-8");
+      // modify data with string methods
+
+    } else if (accept.binary.indexOf(file.mediaType) > -1) {
+      // binary
+    }
+  }
+}
+ +

Specification

+ +

Not part of any specification.

+ +

See also

+ + diff --git a/files/de/web/api/file/index.html b/files/de/web/api/file/index.html new file mode 100644 index 0000000000..17fe3b3ff7 --- /dev/null +++ b/files/de/web/api/file/index.html @@ -0,0 +1,146 @@ +--- +title: File +slug: Web/API/File +tags: + - API + - DOM + - Files +translation_of: Web/API/File +--- +
{{APIRef }}
+ +

DasFile Interface stellt Informationen über Dateien bereit und erlaubt den Zugriff auf deren Inhalt.

+ +

File werden generell von einem {{domxref("FileList")}} Objekt als das Ergebnis einer Benutzerauswahl von Dateien über ein {{ HTMLElement("input") }} Element, von einem DataTransfer Objekt eines Drag-and-Drop-Vorgangs, oder von der mozGetAsFile() API eines {{ domxref("HTMLCanvasElement") }} zurückgegeben. In Gecko ist es von privilegiertem Code aus möglich, den Konstruktor direkt mit einem String Pfad oder einem {{interface("nsIFile")}} aufzurufen. Siehe Using the DOM File API in chrome code für weitere Details.

+ +

Die Dateireferenz kann nach der Formularübermittlung gespeichert werden, während der Benutzer über keine Internetverbindung verfügt. Somit können die Daten empfangen und hochgeladen werden, sobald die Internetverbindung wiederhergestellt ist.

+ +

Properties

+ +

DasFile Interface erbt ebenso von dem {{domxref("Blob")}} Interface.

+ +
+
{{domxref("File.lastModifiedDate")}} {{readonlyinline}} {{gecko_minversion_inline("15.0")}}
+
Das Date der letzten Veränderung der Datei, referenziert durch das File Objekt.
+
{{domxref("File.name")}} {{readonlyinline}} {{gecko_minversion_inline("1.9.2")}}
+
Der Name der Datei, referenziert durch das File Objekt.
+
{{domxref("File.fileName")}} {{non-standard_inline}} {{readonlyinline}} {{obsolete_inline("7.0")}}
+
Der Name der Datei, referenziert durch das File Objekt.
+
{{domxref("File.fileSize")}} {{non-standard_inline}} {{readonlyinline}} {{obsolete_inline("7.0")}}
+
Die Größe der Datei in Bytes.
+
+ +

Methods

+ +

The File interface also inherits methods from the {{domxref("Blob")}} interface.

+ +
+
{{domxref("File.getAsBinary()")}} {{non-standard_inline}} {{obsolete_inline("7.0")}}
+
Returns a string containing the file's data in raw binary format.
+
{{domxref("File.getAsDataURL()")}} {{non-standard_inline}} {{obsolete_inline("7.0")}}
+
A string containing the file's data encoded as a data: URL.
+
{{domxref("File.getAsText()","File.getAsText(string encoding)")}} {{non-standard_inline}} {{obsolete_inline("7.0")}}
+
Returns the file's contents as a string in which the file's data is interpreted as text using a given encoding.
+
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('File API')}}{{Spec2('File API')}}Initial definition.
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support13{{CompatGeckoDesktop("1.9")}} (non standard)
+ {{CompatGeckoDesktop("7")}} (standard)
10.011.56.0
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
basic support{{CompatNo}}25{{CompatNo}}11.16.0
+
+ +

Implementation notes

+ +

Gecko notes

+ + + +

Chrome Code - Scope Availability

+ +

To use from chrome code, JSM and Bootstrap scope, you have to import it like this:

+ +
Cu.importGlobalProperties(['File']);
+
+ +

URL is available in Worker scopes.

+ +

See also

+ + diff --git a/files/de/web/api/file/name/index.html b/files/de/web/api/file/name/index.html new file mode 100644 index 0000000000..ffdb12db0f --- /dev/null +++ b/files/de/web/api/file/name/index.html @@ -0,0 +1,104 @@ +--- +title: File.name +slug: Web/API/File/name +tags: + - DOM + - Files +translation_of: Web/API/File/name +--- +

{{APIRef("File API")}}

+ +

Gibt den Namen der File zurück. Aus Sicherheitsgründen wird der Pfad der Datei nicht mit zurückgegeben.

+ +

Syntax

+ +
var name = instanceOfFile.name
+ +

Value

+ +

Ein string, der den Namen der File ohne Pfad beinhaltet, bspw. "My Resume.rtf".

+ +

Beispiel

+ +
// fileInput is a HTMLInputElement: 
+var fileInput = document.getElementById("myfileinput");
+
+// files is a FileList object (simliar to NodeList)
+var files = fileInput.files;
+
+for (var i = 0; i < files.length; i++) {
+  alert("Filename " + files[i].name);
+}
+ +

Spezifikationen

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('File API', '#file-attrs', 'name')}}{{Spec2('File API')}}Initial definition.
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
File.name13.0{{CompatGeckoDesktop("1.9.2")}}10.016.0{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
File.name{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

Siehe auch

+ + diff --git a/files/de/web/api/file/typ/index.html b/files/de/web/api/file/typ/index.html new file mode 100644 index 0000000000..28c57a4cb1 --- /dev/null +++ b/files/de/web/api/file/typ/index.html @@ -0,0 +1,65 @@ +--- +title: File.type +slug: Web/API/File/Typ +translation_of: Web/API/File/type +--- +
{{APIRef("File API")}}
+ +

Gibt den Internet Media Typ (MIME) einer Datei zurück, welche durch ein {{domxref("File")}} Objekt dargestellt wird.

+ +

Syntax

+ +
var name = file.type;
+ +

Wert

+ +

Eine Zeichenkette, welche den Internet Media Typ (MIME) enthält und den Typ der Datei angibt, zum Beispiel "image/png" für ein PNG Bild

+ +

Beispiel

+ +
<input type="file" multiple onchange="showType(this)">
+
+ +
function showType(fileInput) {
+  var files = fileInput.files;
+
+  for (var i = 0; i < files.length; i++) {
+    var name = files[i].name;
+    var type = files[i].type;
+    alert("Filename: " + name + " , Type: " + type);
+  }
+}
+ +

Hinweis: Basierend auf der aktuellen Implementierung, lesen Browser nicht wirklich den Bytestrom einer Datei, um ihren Medientyp zu bestimmen. Es wird aufgrund der Dateiendung angenommen; eine PNG-Bilddatei, die in .txt umbenannt wird, würde "text/plain" und nicht "image/png" ergeben. Darüber hinaus ist file.type im Allgemeinen nur für gängige Dateitypen wie Bilder, HTML-Dokumente, Audio und Video zuverlässig. Seltene Dateierweiterungen würden eine leere Zeichenkette zurückgeben. Die Client-Konfiguration (z.B. die Windows-Registrierung) kann auch bei gängigen Typen zu unerwarteten Werten führen. Entwicklern wird empfohlen, sich nicht auf diese Eigenschaft als einziges Validierungsschema zu verlassen.

+ +

Spezifikation

+ + + + + + + + + + + + + + + + +
SpezifikationStatusKommentar
{{SpecName('File API', '#dfn-type', 'type')}}{{Spec2('File API')}}Initiale Definition.
+ +

Browser-Kompatibilität

+ + + +

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

+ +

Siehe auch

+ + diff --git a/files/de/web/api/file/zugriff_auf_dateien_von_webapplikationen/index.html b/files/de/web/api/file/zugriff_auf_dateien_von_webapplikationen/index.html new file mode 100644 index 0000000000..c44ac4b9df --- /dev/null +++ b/files/de/web/api/file/zugriff_auf_dateien_von_webapplikationen/index.html @@ -0,0 +1,512 @@ +--- +title: Zugriff auf Dateien von Webapplikationen +slug: Web/API/File/Zugriff_auf_Dateien_von_Webapplikationen +translation_of: Web/API/File/Using_files_from_web_applications +--- +

Mithilfe der File API, welche mit HTML5 zum DOM hinzugefügt wurde, ist es nun für Webinhalte möglich den Benutzer lokale Dateien auswählen zu lassen und den Inhalt dieser Dateien auszulesen. Die Auswahl kann entweder durch das HTML Element {{ HTMLElement("input") }} oder durch Drag and Drop erfolgen.

+ +

Es ist auch möglich die DOM File API von Erweiterungen oder anderem Chrome Code zu benutzen. In diesem Fall müssen einige zusätzliche Dinge beachtet werden, die im Abschnitt Using the DOM File API in chrome code näher erläutert werden.

+ +

Auf ausgewählte Dateien zugreifen

+ +

Gehen wir von folgendem HTML-Code aus:

+ +
<input type="file" id="input">
+ +

Die File API erlaubt den Zugriff auf eine {{ domxref("FileList") }} mit {{ domxref("File") }} Objekten, die die vom Benutzer ausgewählten Dateien repräsentieren.

+ +

Wenn der Benutzer nur eine Datei auswählt, dann muss nur die erste Datei in der Liste betrachtet werden.

+ +

Eine ausgewählte Datei erhält man über den üblichen DOM Selektor:

+ +
var selectedFile = document.getElementById('input').files[0];
+ +

Oder mit einem jQuery Selektor:

+ +
var selectedFile = $('#input').get(0).files[0];
+
+var selectedFile = $('#input')[0].files[0];
+ +
+

Tritt der Fehler "files is undefined" auf:
+ Es wurde das falsche HTML element ausgewählt. Es ist zu beachten, dass ein jQuery Selektor eine Liste von zutreffenden DOM Elementen zurückliefert. Das richtige DOM Element muss ausgewählt werden, um "files" darauf anzuwenden.

+
+ +

Zugriff auf ausgewählte Dateien über den Change Event

+ +

Es ist auch möglich (aber nicht unbedingt erforderlich), auf die {{ domxref("FileList") }} über das change event zuzugreifen:

+ +
<input type="file" id="input" onchange="handleFiles(this.files)">
+ +

Wenn der Benutzer eine Datei auswählt, wird die Funktion handleFiles() aufgerufen. Als Parameter wird die {{ domxref("FileList") }} übergeben. Sie enthält die {{ domxref("File") }} Objekte, die die vom Benutzer ausgewählten Dateien repräsentieren.

+ +

Soll der Benutzer mehrere Dateien auswählen können, dann kann einfach das Attribut multiple auf das input Element angewendet werden:

+ +
<input type="file" id="input" multiple onchange="handleFiles(this.files)">
+ +

In diesem Fall enthält die Dateiliste, die an die handleFiles() Funktion übergeben wird, ein {{ domxref("File") }} für jede Datei, die der Benutzer ausgewählt hat.

+ +

Dynamisch einen Change Listener hinzufügen

+ +

Wurde das input Feld mit einer JavaScript Bibliothek wie jQuery erzeugt, dann muss der event Listener mit {{ domxref("element.addEventListener()") }} hinzugefügt werden:

+ +
var inputElement = document.getElementById("input");
+inputElement.addEventListener("change", handleFiles, false);
+function handleFiles() {
+  var fileList = this.files; /* Jetzt kann die Dateiliste verarbeitet werden */
+}
+ +

In diesem Fall ist die handleFiles() Funktion selbst der Event Handler, anders als in den vorigen Beispielen, wo sie von einem Event Handler aufgerufen wurde.

+ +

Informationen über die ausgewählte(n) Datei(en)

+ +

Das {{ domxref("FileList") }} Objekt, das vom DOM geliefert wurde, enthält eine Liste aller Dateien, die vom Benutzer ausgewählt wurden. Jede der Dateien wird durch ein {{ domxref("File") }} Objekt repräsentiert. Die Anzahl der ausgewälten Dateien kann über das length Attribut der Liste ermittelt werden:

+ +
var numFiles = files.length;
+ +

Die einzelnen {{ domxref("File") }} Objekte erhält man, indem das {{ domxref("FileList") }} Objekt einfach wie ein Array behandelt wird:

+ +
for (var i = 0, numFiles = files.length; i < numFiles; i++) {
+  var file = files[i];
+  ..
+}
+
+ +

Diese Schleife iteriert über alle Dateien in der Liste.

+ +

Im {{ domxref("File") }} Objekt liefern drei Attribute hilfreiche Informationen über die Datei:

+ +
+
name
+
Der Dateiname als read-only String. Es ist nur der Dateiname enthalten, keine Pfadinformationen.
+
size
+
Die Dateigröße in Bytes als read-only 64-Bit Integer.
+
type
+
Der MIME type der Datei als read-only String oder "", wenn der Typ nicht ermittelt werden konnte.
+
+ +

Beispiel: Dateigröße anzeigen

+ +

Das folgende Beispiel zeigt eine mögliche Verwendung des size Attributs:

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

Verstecktes input Element mit click() Methode

+ +

Ab Gecko 2.0 {{ geckoRelease("2.0") }}, kann das zugegebenermaßen hässliche Datei-{{ HTMLElement("input") }} Element versteckt und durch eigene Oberflächenelemente zum Zugriff auf den Datei-Öffnen-Dialog ersetzt werden. Dazu wird das input Element mit dem CSS Stil display:none versehen und mit der Methode {{ domxref("element.click","click()") }} aufgerufen.

+ +

Gehen wir von folgendem HTML-Code aus:

+ +
<input type="file" id="fileElem" multiple accept="image/*" style="display:none" onchange="handleFiles(this.files)">
+<a href="#" id="fileSelect">Bitte Dateien auswählen</a>
+
+
+ +

Der Code, der auf den click Event reagiert, kann wie folgt aussehen:

+ +
var fileSelect = document.getElementById("fileSelect"),
+  fileElem = document.getElementById("fileElem");
+
+fileSelect.addEventListener("click", function (e) {
+  if (fileElem) {
+    fileElem.click();
+  }
+  e.preventDefault(); // prevent navigation to "#"
+}, false);
+
+ +

Das neue Oberflächenelement zum Zugriff auf den Datei-Öffnen-Dialog kann nun beliebig gestaltet werden.

+ +

label Element zum Auslösen eines versteckten input Elements

+ +

Wird statt eines Links ({{ HTMLElement("a") }} Element) ein {{ HTMLElement("label") }} Element verwendet, dann kann das versteckte input Element auch ohne JavaScript ausgelöst werden. Dabei darf das input-Element aber weder mit display: none noch mit visibility: hidden versteckt werden, weil es in diesen Fällen nicht mit der Tastatur bedienbar wäre. Es darf nur visuell versteckt werden.

+ +

Gehen wir von folgendem HTML-Code aus:

+ +
<input type="file" id="fileElem" multiple accept="image/*" class="visually-hidden">
+<label for="fileElem">Bitte Dateien auswählen</label>
+
+ +

und folgendem CSS:

+ +
.visually-hidden {
+  position: absolute !important;
+  height: 1px;
+  width: 1px;
+  overflow: hidden;
+  clip: rect(1px, 1px, 1px, 1px);
+}
+
+input.visually-hidden:focus + label {
+  outline: thin dotted;
+}
+
+ +

Bei einem Klick auf das label Element wird der Datei-Öffnen-Dialog angezeigt.

+ +

Das label Element kann per CSS beliebig gestaltet werden. Man muss aber das Label des versteckten Eingabefelds hervorheben, wenn dieses den Fokus hat, d.h. per Tab-Taste angewählt wurde – sei es durch outline wie im obigen Beispiel oder background-color oder box-shadow. (Gegenwärtig stellt Firefox das Label von fokussierten <input type="file">-Elementen nicht hervorgehoben dar.)

+ +

Dateien per Drag and Drop auswählen

+ +

Es ist auch möglich, per Drag and Drop Dateien an die Webanwendung zu übergeben.

+ +

Zuerst muss eine Drop Zone eingerichtet werden. Welcher Teil der Oberfläche Drops entgegen nimmt, ist vom Design der Anwendung abhängig. Generell ist das Empfangen von Drop Events aber einfach:

+ +
var dropbox;
+
+dropbox = document.getElementById("dropbox");
+dropbox.addEventListener("dragenter", dragenter, false);
+dropbox.addEventListener("dragover", dragover, false);
+dropbox.addEventListener("drop", drop, false);
+
+ +

In diesem Beispiel wird das Element mit der ID dropbox als Drop Zone verwendet. Das wird durch Registrieren der Listener für {{event('dragenter')}}, {{event('dragover')}} und {{event('drop')}} Events erreicht.

+ +

dragenter und dragover benötigen wir in unserem Fall eigentlich nicht. Wir verhindern lediglich eine weitere Behandlung der Events durch Aufruf von e.stopPropagation() und e.preventDefault():

+ +
function dragenter(e) {
+  e.stopPropagation();
+  e.preventDefault();
+}
+
+function dragover(e) {
+  e.stopPropagation();
+  e.preventDefault();
+}
+
+ +

Das Wesentliche geschieht in der Behandlung des drop Events:

+ +
function drop(e) {
+  e.stopPropagation();
+  e.preventDefault();
+
+  var dt = e.dataTransfer;
+  var files = dt.files;
+
+  handleFiles(files);
+}
+
+ +

Hier ermitteln wir das dataTransfer Feld aus dem Event, entnehmen ihm die Dateiliste und übergeben diese an handleFiles(). Von da an ist die Weiterverarbeitung die gleiche wie bei Verwendung des input Elements.

+ +

Beispiel: Thumbnails von ausgewählten Bildern anzeigen

+ +

Gehen wir davon aus, dass auf einer Foto-Webseite mit HTML5 eine Thumbnail Vorschau von Bildern angezeigt werden soll, bevor sie hochgeladen werden. Das input Element oder die Drop Zone kann wie oben beschrieben eingerichtet werden. Diese rufen die folgende handleFiles() Funktion auf:

+ +
function handleFiles(files) {
+  for (var i = 0; i < files.length; i++) {
+    var file = files[i];
+    var imageType = /^image\//;
+
+    if (!imageType.test(file.type)) {
+      continue;
+    }
+
+    var img = document.createElement("img");
+    img.classList.add("obj");
+    img.file = file;
+    preview.appendChild(img); // Gehen wird davon aus, dass "preview" das div-Element ist, in dem der Inhalt angezeigt wird.
+
+    var reader = new FileReader();
+    reader.onload = (function(aImg) { return function(e) { aImg.src = e.target.result; }; })(img);
+    reader.readAsDataURL(file);
+  }
+}
+
+ +

Mit der Schleife wird über die ausgewählten Dateien iteriert. Bei jeder Datei wird mit Hilfe des type Attributs (indem der Reguläre Ausdruck "^image\/" darauf angewendet wird) geprüft, ob es sich um eine Bild Datei handelt. Liegt eine Bild Datei vor, dann wird ein neues img Element erzeugt. Mit CSS können z.B. hübsche Ränder oder Schatten erzeugt und die Größe des Bildes festgelegt werden, das muss also nicht hier im Code erfolgen.

+ +

Jedem Bild wird die CSS Klasse obj zugewiesen, so dass es einfach ist, es im DOM Baum zu finden. Außerdem wird jedem Bild im file Attribut das {{ domxref("File") }} Objekt für das Bild zugewiesen; das benötigen wir später für den tatsächlichen Upload der Datei. Mit {{ domxref("Node.appendChild()") }} wird das neue Thumbnail dem preview Bereich unserer Anwendung hinzugefügt.

+ +

Dann erstellen wir einen {{ domxref("FileReader") }}, um das Bild asynchron zu laden und es dem img Element hinzuzufügen. Nach dem Erstellen des FileReader Objektes definieren wir die onload Funktion und rufen readAsDataURL() auf, um die Leseoperation im Hintergrund zu starten. Ist der komplette Inhalt der Bilddatei geladen, dann wird er in eine data: URL umgewandelt, die an den onload Callback übergeben wird. Unsere Implementation dieser Routine setzt das src Attribut des img Elements auf das geladene Bild, was dazu führt, dass das Bild im Thumbnail auf dem Bildschirm des Benutzers erscheint.

+ +

Verwendung von Objekt URLs

+ +

Mit Gecko 2.0 {{ geckoRelease("2.0") }} wurde die Unterstützung für die DOM Methoden {{ domxref("window.URL.createObjectURL()") }} und {{ domxref("window.URL.revokeObjectURL()") }} eingeführt. Mit ihnen lassen sich einfache URL Strings erzeugen, die beliebige Daten referenzieren, auf die per DOM {{ domxref("File") }} Objekte zugegriffen werden kann; einschließlich lokale Dateien auf dem Computer des Anwenders.

+ +

Wenn man aus HTML mit einer URL auf ein {{ domxref("File") }} Objekt verweisen möchte, dann kann man dafür eine Objekt URL erzeugen:

+ +
var objectURL = window.URL.createObjectURL(fileObj);
+ +

Die Objekt URL ist ein String, der das {{ domxref("File") }} Objekt identifiziert. Jedes Mal, wenn {{ domxref("window.URL.createObjectURL()") }} aufgerufen wird, wird eine eindeutige Objekt URL erzeugt, auch wenn vorher bereits eine Objekt URL für diese Datei erzeugt wurde. Jede von ihnen muss wieder freigegeben werden. Sie werden automatisch freigegeben, wenn das Dokument entladen wird. Wenn ihre Anwendung die Objekt URLs dynamisch verwendet, dann sollten Sie sie auch explizit durch Aufruf von {{ domxref("window.URL.revokeObjectURL()") }} freigeben:

+ +
window.URL.revokeObjectURL(objectURL);
+ +

Beispiel: Mit Objekt URLs Bilder anzeigen

+ +

Dieses Beispiel verwendet Objekt URLs, um Thumbnails von Bildern anzuzeigen. Darüber hinaus werden weitere Dateiinformationen einschließlich Name und Größe angezeigt. Live Ansicht des Beispiels.

+ +

Das HTML für die Oberfläche sieht folgendermaßen aus:

+ +
<input type="file" id="fileElem" multiple accept="image/*" style="display:none" onchange="handleFiles(this.files)">
+<a href="#" id="fileSelect">Bitte Dateien auswählen</a>
+<div id="fileList">
+  <p>Keine Dateien ausgewählt!</p>
+</div>
+
+ +

Das erstellt ein Datei {{ HTMLElement("input") }} Element, zusammen mit einem Link, der den Datei-Öffnen-Dialog anzeigt (so kann das Datei input Element versteckt werden, da es nicht so attraktiv aussieht). Das wird oben im Abschnitt {{ anch("Verstecktes input Element mit click() Methode") }} näher beschrieben.

+ +

Die handleFiles() Methode sieht folgendermaßen aus:

+ +
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() {
+        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);
+    }
+  }
+}
+
+ +

Das {{ HTMLElement("div") }} Element mit der ID fileList wird ermittelt. Das ist der Block, in den wir später unsere Dateiliste einschließlich Thumbnails einfügen.

+ +

Ist das {{ domxref("FileList") }} Objekt, das an handleFiles() übergeben wird, null, dann wird einfach "No files selected!" ausgegeben. Ansonsten bauen wir unsere Dateiliste wie folgt:

+ +
    +
  1. Ein neues ({{ HTMLElement("ul") }}) Element wird erzeugt.
  2. +
  3. Das neue Listenelement wird dem {{ HTMLElement("div") }} Block hinzugefügt durch Aufruf der {{ domxref("element.appendChild()") }} Methode.
  4. +
  5. Für jedes {{ domxref("File") }} in der {{ domxref("FileList") }}, die durch files repräsentiert wird: +
      +
    1. Erzeuge ein neues Listenelement ({{ HTMLElement("li") }}) und füge es der Liste hinzu.
    2. +
    3. Erzeuge ein neues Bildelement ({{ HTMLElement("img") }}).
    4. +
    5. Setze das src Attribut des Bildes auf die neue Objekt URL, die die Datei repräsentiert, wobei die Objekt URL mit {{ domxref("window.URL.createObjectURL()") }} erzeugt wird.
    6. +
    7. Setze die Bildgröße auf 60 Pixel.
    8. +
    9. Richte den onload Event Handler ein, um die Objekt URL wieder freizugeben, da sie nach dem Laden des Bildes nicht mehr benötigt wird. Das wird durch Aufruf der Methode {{ domxref("window.URL.revokeObjectURL()") }} und Übergabe des Objekt URL Strings aus img.src gemacht.
    10. +
    11. Füge das neue Bildelement dem Listenelement hinzu.
    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 built 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 allows us to select all of 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 fetches a {{ domxref("NodeList") }}, called imgs, of all the elements in the document with the CSS class obj. In our case, these will be all of the image thumbnails. Once we have that list, it's trivial to go through it and create 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, and 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 progress information to 100% 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. +
+ +
Note: The non-standard sendAsBinary method in the example above is considered deprecated as of Gecko 31 {{ geckoRelease(31) }} and will be removed soon. The standard send(Blob data) method can be used instead.
+ +

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

Example: Using object URLs to display PDF

+ +

Object URLs can be used for other things than just images! They can be used to display embedded PDF files or any other resources that can be displayed by the browser.

+ +

In Firefox, to have the PDF appear embedded in the iframe (rather than proposed as a downloaded file), the preference pdfjs.disabled must be set to false {{non-standard_inline()}}.

+ +
<iframe id="viewer">
+
+ +

And here is the change of the src attribute:

+ +
var obj_url = window.URL.createObjectURL(blob);
+var iframe = document.getElementById('viewer');
+iframe.setAttribute('src', obj_url);
+window.URL.revokeObjectURL(obj_url);
+ +

Example: Using object URLs with other file types

+ +

You can manipulate files of other formats the same way. Here is how to preview uploaded video:

+ +
var video = document.getElementById('video');
+var obj_url = window.URL.createObjectURL(blob);
+video.src = obj_url;
+video.play()
+window.URL.revokeObjectURL(obj_url);
+ +

Specifications

+ + + +

See also

+ + + +

{{ HTML5ArticleTOC() }}

+ +

{{ languages( { "zh-cn": "zh-cn/Using_files_from_web_applications", "ja": "ja/Using_files_from_web_applications" } ) }}

diff --git a/files/de/web/api/filereader/index.html b/files/de/web/api/filereader/index.html new file mode 100644 index 0000000000..b7c8668c3a --- /dev/null +++ b/files/de/web/api/filereader/index.html @@ -0,0 +1,153 @@ +--- +title: FileReader +slug: Web/API/FileReader +translation_of: Web/API/FileReader +--- +
{{APIRef("File API")}}
+ +

Mit dem FileReader-Objekt können Webapplikationen den Inhalt von auf dem Computer des Benutzers gespeicherten Dateien (oder Rohdaten-Buffer) asynchron lesen. Mit {{domxref("File")}} oder {{domxref("Blob")}}-Objekten wird die zu lesende Datei oder die zu lesenden Daten spezifiziert.

+ +

File Objekte können über ein {{domxref("FileList")}} Objekt erhalten werden, welches als Ergebnis einer Dateiauswahl durch einen Benutzer über das {{HTMLElement("input")}} Element zurückgegeben wird. Weitere mögliche Quellen sind drag and drop Ereignisse über ein DataTransfer Objekt oder über die mozGetAsFile() API des {{domxref("HTMLCanvasElement")}}.

+ +

Konstruktor

+ +
FileReader FileReader();
+ +

Im Kapitel Zugriff auf Dateien von Webapplikationen finden sich weitere Details und Beispiele.

+ +

Eigenschaften

+ +
+
{{domxref("FileReader.error")}} {{readonlyinline}}
+
Ein {{domxref("DOMError")}}, der den Fehler angibt, welcher beim Lesen der Datei entstanden ist.
+
{{domxref("FileReader.readyState")}} {{readonlyinline}}
+
Eine Zahl, welche den Status des FileReader angibt. Möglich ist eine der {{anch("Status-Konstanten")}}.
+
{{domxref("FileReader.result")}} {{readonlyinline}}
+
Der Inhalt der Datei. Diese Eigenschaft ist nur gültig, nachdem der Lesevorgang abgeschlossen ist. Das Format der Daten hängt davon ab, welche der Methoden zum Starten des Lesevorgangs benutzt wurde.
+
+ +

Event-Handler

+ +
+
{{domxref("FileReader.onabort")}}
+
Ein Handler für das {{event("abort")}}-Event. Dieser Event wird gefeuert, wenn der Lesevorgang abgebrochen wird.
+
{{domxref("FileReader.onerror")}}
+
Ein Handler für das {{event("error")}}-Event. Dieser Event wird gefeuert, wenn beim Lesevorgang ein Fehler ensteht.
+
{{domxref("FileReader.onload")}}
+
Ein Handler für das {{event("load")}}-Event. Dieser Event wird gefeuert, wenn der Lesevorgang erfolgreich beendet wird.
+
{{domxref("FileReader.onloadstart")}}
+
Ein Handler für das {{event("loadstart")}}-Event. Dieser Event wird gefeuert, wenn der Lesevorgang gestartet wird.
+
{{domxref("FileReader.onloadend")}}
+
Ein Handler für das {{event("loadend")}}-Event. Dieser Event wird gefeuert, wenn der Lesevorgang beendet wird (entweder erfolgreich oder fehlerhaft).
+
{{domxref("FileReader.onprogress")}}
+
Ein Handler für das {{event("progress")}}-Event. Dieser Event wird gefeuert, während ein {{domxref("Blob")}}-Inhalt gelesen wird.
+
+ +
+

Hinweis: DaFileReader von {{domxref("EventTarget")}} erbt, kann auf alle diese Events auch mit der {{domxref("EventTarget.addEventListener()","addEventListener")}} Methode gehört werden.

+
+ +

Status-Konstanten

+ + + +

Methoden

+ +
+
{{domxref("FileReader.abort()")}}
+
Bricht den Lesevorgang ab. Nach dem Return wird der readyState zu DONE.
+
{{domxref("FileReader.readAsArrayBuffer()")}} {{gecko_minversion_inline("7.0")}}
+
Startet den Lesevorgang und liest den spezifierten {{domxref("Blob")}} und, wenn der Lesevorgang abgeschlossen ist, enthält result ein {{domxref("ArrayBuffer")}} mit den Daten.
+
{{domxref("FileReader.readAsBinaryString()")}}
+
Startet den Lesevorgang und liest den spezifierten {{domxref("Blob")}} und, wenn der Lesevorgang abgeschlossen ist, enthält result die rohen Binär-Daten als String.
+
{{domxref("FileReader.readAsDataURL()")}}
+
Startet den Lesevorgang und liest den spezifierten {{domxref("Blob")}} und, wenn der Lesevorgang abgeschlossen ist, enthält result die Daten als Data-URL.
+
{{domxref("FileReader.readAsText()")}}
+
Startet den Lesevorgang und liest den spezifierten {{domxref("Blob")}} und , wenn der Lesevorgang abgeschlossen ist, enthält result die Daten als Text-String.
+
+ +

Spezifikationen

+ + + + + + + + + + + + + + +
SpezifikationStatusKommentar
{{SpecName("File API", "#FileReader-interface", "FileReader")}}{{Spec2("File API")}}Initial definition
+ +

Browser-Kompatiblität

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureFirefox (Gecko)ChromeInternet ExplorerOperaSafari
Basissupport{{CompatGeckoDesktop("1.9.2")}}[1]710[2]12.02[3]6.0.2
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureFirefox Mobile (Gecko)AndroidIE MobileOpera MobileSafari Mobile
Basissupport3231011.56.1
+
+ +

[1] Vor Gecko 2.0 beta 7 (Firefox 4.0 beta 7), waren alle {{domxref("Blob")}} parameters stattdessen {{domxref("File")}} Parameter; Das wurde aktualisiert um die Spezifikation zu erfüllen. Vor Gecko 13.0 {{geckoRelease("13.0")}} gab die FileReader.error Eigenschaft ein  {{domxref("FileError")}} Objekt zurück. Dieses Interface wurde wurde entfernt und FileReader.error gibt nun einen {{domxref("DOMError")}} Objekt zurück, wie in dem aktuellen FileAPI Entwurf vorgesehen.

+ +

[2] IE9 hat ein File API Lab.

+ +

[3] Opera hat partiellen Support in 11.1.

+ +

Siehe auch

+ + diff --git a/files/de/web/api/filereader/onload/index.html b/files/de/web/api/filereader/onload/index.html new file mode 100644 index 0000000000..95dda3e59f --- /dev/null +++ b/files/de/web/api/filereader/onload/index.html @@ -0,0 +1,24 @@ +--- +title: onload +slug: Web/API/FileReader/onload +tags: + - Dateien + - Lesen +translation_of: Web/API/FileReader/onload +--- +

Das onload Event wird ausgelöst, wenn der Inhalt von readAsArrayBuffer, readAsBinaryString, readAsDataURL or readAsText verfügbar ist.

+ +

Beispiel

+ +
// Callback von einem <input type="file" onchange="onChange(event)">
+function onChange(event) {
+  var file = event.target.files[0];
+  var reader = new FileReader();
+  reader.onload = function(event) {
+    // Hier wird der Text der Datei ausgegeben
+    console.log(event.target.result)
+  };
+
+  reader.readAsText(file);
+}
+
diff --git a/files/de/web/api/formdata/formdata/index.html b/files/de/web/api/formdata/formdata/index.html new file mode 100644 index 0000000000..40ce36053f --- /dev/null +++ b/files/de/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")}}

+ +

Der FormData() Konstruktor erzeugt ein neues {{domxref("FormData")}}-Objekt.

+ +
+

Anmerkung: Dieses Feature is verfügbar auf Web Workers.

+
+ +

Syntax

+ +
var formData = new FormData(form)
+ +

Parameter

+ +
+
form {{optional_inline}}
+
Ein HTML {{HTMLElement("form")}}-Element — wenn angegeben, wird  das neue {{domxref("FormData")}}-Objekt mit den aktuellen Schlüssel/Wert-Paaren des form's gefüllt, wobei "name" der Schlüssel und "value" der Wert. Mitgeschickte Dateien werden ebenfalls codiert.
+
+ +

Example

+ +

So erzeugt man ein neues FormData-Objekt:

+ +
var formData = new FormData(); // leer
+ +

Nun kann man ein Schlüssel/Wert-Paar hinzufügen mit {{domxref("FormData.append")}}:

+ +
formData.append('username', 'Chris');
+
+ +

Oder man gibt das optionale form Argument an, um es direkt mit dessen Werten zu füllen:

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

Anmerkung: Alle input-Elemente haben das 'name'-Attribut. Das ist notwendig um die Werte auszuwerten.

+
+ +
var myForm = document.getElementById('myForm');
+formData = new FormData(myForm);
+ +

Spezifikationen

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('XMLHttpRequest','#dom-formdata','FormData()')}}{{Spec2('XMLHttpRequest')}}Initial definition
+ +

Browserkompatibilität

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

+ +

See also

+ + +
diff --git a/files/de/web/api/formdata/get/index.html b/files/de/web/api/formdata/get/index.html new file mode 100644 index 0000000000..1bcd503006 --- /dev/null +++ b/files/de/web/api/formdata/get/index.html @@ -0,0 +1,145 @@ +--- +title: FormData.get() +slug: Web/API/FormData/get +translation_of: Web/API/FormData/get +--- +

{{APIRef("XMLHttpRequest")}}

+ +

Die get() Methode der {{domxref("FormData")}} Schnittstelle gibt die den ersten Wert, der dem gegebenen Schlüssel zugeordnet ist, aus dem FormData Objekt zurück. Wenn mehrere Werte zu erwarten sind und diese alle verwendet werden sollen, sollte stattdeessen die Methode {{domxref("FormData.getAll()","getAll()")}} verwendet werden.

+ +
+

Hinweis: Diese Methode ist in Web Workers verfügbar.

+
+ +

Syntax

+ +
formData.get(name);
+ +

Parameter

+ +
+
name
+
Ein {{domxref("USVString")}}, der den Namen des abzurufenden Schlüssels repräsentiert.
+
+ +

Rückgabewert

+ +

Ein {{domxref("FormDataEntryValue")}}, der den Wert enthält.

+ +

Example

+ +

Die folgende Zeile erzeugt ein leeres FormData Objekt:

+ +
var formData = new FormData();
+ +

Wenn man zwei Werte als benutzername mit {{domxref("FormData.append")}} hinzufügt:

+ +
formData.append('benutzername', 'Chris');
+formData.append('benutzername', 'Bob');
+ +

Der folgende Aufruf der get() Funktion liefert dann nur den zuerst hinzugefügten Wert für benutzername:

+ +
formData.get('benutzername'); // Gibt "Chris" zurück
+ +

Spezifikationen

+ + + + + + + + + + + + + + +
SpezifikationStatusKommentar
{{SpecName('XMLHttpRequest','#dom-formdata-get','get()')}}{{Spec2('XMLHttpRequest')}} 
+ +

Browserkompatibilität

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Grundlegende Unterstützung{{CompatChrome(50.0)}}{{CompatGeckoDesktop('39.0')}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}
Verfügbar in web workers{{CompatChrome(50.0)}}{{CompatGeckoDesktop('39.0')}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)Firefox OS (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
Grundlegende Unterstützung{{CompatNo}}{{CompatChrome(50.0)}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatNo}} +

{{CompatVersionUnknown}}

+
{{CompatNo}}{{CompatChrome(50.0)}}
Verfügbar in web workers{{CompatNo}}{{CompatChrome(50.0)}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatChrome(50.0)}}
+
+ +

Siehe auch

+ + diff --git a/files/de/web/api/formdata/getall/index.html b/files/de/web/api/formdata/getall/index.html new file mode 100644 index 0000000000..09cdc69036 --- /dev/null +++ b/files/de/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")}}

+ +

Die getAll() Methode der  {{domxref("FormData")}} Schnittstelle gibt alle Werte zurück, die innerhalb eines FormData Objekts mit einem gegebenen Schlüssel assoziiert sind.

+ +
+

Hinweis: Diese Methode ist in Web Workers verfügbar.

+
+ +

Syntax

+ +
formData.getAll(name);
+ +

Parameter

+ +
+
name
+
Ein {{domxref("USVString")}}, der den Namen des Schlüssels darstellt, der abgerufen werden soll.
+
+ +

Rückgabewerte

+ +

Ein Array von {{domxref("FormDataEntryValue")}}s.

+ +

Beispiel

+ +

Die folgende Zeile erstellt ein leeres FormData Objekt:

+ +
var formData = new FormData();
+ +

Hinzufügen von zwei username Werten mit Hilfe von {{domxref("FormData.append")}}:

+ +
formData.append('username', 'Chris');
+formData.append('username', 'Bob');
+ +

Der darauffolgende Aufruf der getAll() Funktion gibt beide username Werte in einem Array zurück.:

+ +
formData.getAll('username'); // gibt ["Chris", "Bob"] zurück
+ +

Spezifikation

+ + + + + + + + + + + + + + +
SpezifikationStatusKommentar
{{SpecName('XMLHttpRequest','#dom-formdata-getall','getAll()')}}{{Spec2('XMLHttpRequest')}} 
+ +

Browser Kompatibilität

+ + + +

{{Compat("api.FormData.getAll")}}

+ +

Siehe auch

+ + diff --git a/files/de/web/api/formdata/index.html b/files/de/web/api/formdata/index.html new file mode 100644 index 0000000000..3ff1becbcf --- /dev/null +++ b/files/de/web/api/formdata/index.html @@ -0,0 +1,80 @@ +--- +title: FormData +slug: Web/API/FormData +tags: + - API + - FomData + - Interface + - Referenz + - XMLHttpRequest +translation_of: Web/API/FormData +--- +

{{APIRef("XMLHttpRequest")}}

+ +

Das FormData-Interface ermöglicht das einfache Erstellen eines Objektes bestehend aus Schlüssel/Werte-Paaren, welche Formular-Felder und ihre Werte repräsentieren. Dieses Objekt kann leicht durch das Aufrufen der {{domxref("XMLHttpRequest.send()")}} Methode abgeschickt werden. Es verwendet das gleiche Format wie ein HTML-Formular, dessen Kodierung auf "multipart/form-data" gesetzt wurde.

+ +

Ein Objekt, dass FormData implementiert, kann direkt in den {{jsxref("Statements/for...of", "for...of")}} Strukturen benutzt werden, statt {{domxref('FormData.entries()', 'entries()')}} zu verwenden: for (var p of myFormData) ist identisch zu for (var p of myFormData.entries()).

+ +
+

Hinweis: Dieses Feature ist in  Web Workers verfügbar.

+
+ +

Konstruktor

+ +
+
{{domxref("FormData.FormData","FormData()")}}
+
Erzeugt ein neues FormData-Objekt.
+
+ +

Methoden

+ +
+
{{domxref("FormData.append()")}}
+
Fügt den Wert an den Wert eines bestehenden Schlüssel/Wert-Paares in einem FormData-Objekt an, oder fügt den Schlüssel mit dem Wert hinzu hinzu, falls dieser nicht vorhanden ist.
+
{{domxref("FormData.delete()")}}
+
Löscht ein Schlüssel/Wert-Paar aus einem FormData-Objekt.
+
{{domxref("FormData.entries()")}}
+
Gibt einen {{jsxref("Iteration_protocols","iterator")}} zurück, welcher das Iterieren über alle Schlüssel/Wert-Paare ermöglicht.
+
{{domxref("FormData.get()")}}
+
Gibt den ersten Wert zurück, welcher dem gegebenen Schlüssel in dem FormData-Objekt zugeordnet ist.
+
{{domxref("FormData.getAll()")}}
+
Erstellt ein Array, welches alle dem gegebenen Schlüssel zugeordneten Werte enthält.
+
{{domxref("FormData.has()")}}
+
Gibt einen boolean zurück, welcher Auskunft über das Vorhandenseins des gegeben Schlüssels im FormData-Objekt gibt.
+
{{domxref("FormData.keys()")}}
+
Gibt einen {{jsxref("Iteration_protocols", "iterator")}} zurück, welcher das Iterieren über alle Schlüssel der Schlüssel/Wert-Paare ermöglicht.
+
{{domxref("FormData.set()")}}
+
Ersetzt den Wert für einen bestimmten Schlüssel im FormData-Objekt, oder legt das Schlüssel/Wert-Paar an, sollte der Schlüssel noch nicht existieren.
+
{{domxref("FormData.values()")}}
+
Gibt einen {{jsxref("Iteration_protocols", "iterator")}} zurück, welcher das Iterieren über alle Werte der Schlüsselpaare ermöglicht.
+
+ +

Spezifikationen

+ + + + + + + + + + + + + + +
SpezifikationStatusKommentar
{{SpecName('XMLHttpRequest','#interface-formdata','FormData')}}{{Spec2('XMLHttpRequest')}}FormData definiert in XHR Spezifikation
+ +

Browserkompatibilität

+ +

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

+ +

Siehe auch

+ + diff --git a/files/de/web/api/fullscreenoptions/index.html b/files/de/web/api/fullscreenoptions/index.html new file mode 100644 index 0000000000..a4e76273e3 --- /dev/null +++ b/files/de/web/api/fullscreenoptions/index.html @@ -0,0 +1,43 @@ +--- +title: FullscreenOptions +slug: Web/API/FullscreenOptions +tags: + - API + - Aufbau + - Bildschirm + - Einstellungen + - Full-screen + - Fullscreen API + - FullscreenOptionen + - Navigation + - Optionen + - Referenz + - UI + - Wörterbuch + - fullscreen +translation_of: Web/API/FullscreenOptions +--- +

{{APIRef("Fullscreen API")}}

+ +

Das FullscreenOptions-Wörterbuch wird verwendet, um Konfigurationsoptionen bereitzustellen, wenn {{DOMxRef ("Element.requestFullscreen", "requestFullscreen ()")}} für ein Element aufgerufen wird, um dieses Element in den Vollbildmodus zu versetzen.

+ +

Eigenschaften

+ +
+
{{DOMxRef("FullscreenOptions.navigationUI", "navigationUI")}}{{Optional_Inline}}
+
Eine Zeichenfolge, mit der gesteuert wird, ob die Elemente der Browser-Benutzeroberfläche im Vollbildmodus angezeigt werden sollen. Mit der Standardeinstellung "auto" kann der Browser diese Entscheidung treffen.
+
+ +

Browser-Kompatibilität

+ + + +

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

+ +

Siehe auch

+ + diff --git a/files/de/web/api/gainnode/index.html b/files/de/web/api/gainnode/index.html new file mode 100644 index 0000000000..fb5adeb75e --- /dev/null +++ b/files/de/web/api/gainnode/index.html @@ -0,0 +1,134 @@ +--- +title: GainNode +slug: Web/API/GainNode +translation_of: Web/API/GainNode +--- +

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

+ +
+

Die GainNode Schnittstelle ermöglicht eine Verstärkung (engl. gain) eines Signals, was als veränderte Lautstärke wahrgenommen wird. Es handelt sich um ein {{domxref("AudioNode")}} audio-verarbeitendes Modul, das ein Eingabesignal mit einer gewissen Verstärkung (die auch negativ sein kann) versieht, und es an den Ausgang weiterleitet. Ein GainNode hat immer genau einen Eingang und einen Ausgang, beide mit derselben Anzahl an Kanälen.

+
+ +

Verstärkung ist ein Wert ohne Einheit, der sich über die Zeit ändert. Er wird mit allen zeitlich korrespondierenden Samples aller Eingangskanäle multipliziert, um das Signal zu verändern.  Ändert sich der Wert, wird der neue Wert durch einen "de-zippering" Algorithmus angewendet, um unästhetisches Klick-Artifakte im Signal zu vermeiden.

+ +

The GainNode is increasing the gain of the output.

+ + + + + + + + + + + + + + + + + + + + + + + + +
Anzahl der Eingänge1
Anzahl der Ausgänge1
Kanalzählmethode"max"
Anzahl Kanäle2 (not used in the default count mode)
Kanalinterpretation"speakers"
+ +

Eigenschaften

+ +

Inherits properties from its parent, {{domxref("AudioNode")}}.

+ +
+
{{domxref("GainNode.gain")}} {{readonlyinline}}
+
Ist ein a-rate {{domxref("AudioParam")}} der das Ausmaß der Verstärkung angibt.
+
+ +

Methoden

+ +

Keine spezifischen Methoden; erbt die Methoden der Elternklasse , {{domxref("AudioNode")}}.

+ +

Beispiel

+ +

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

+ +

Spezifikationen

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Audio API', '#the-gainnode-interface', 'GainNode')}}{{Spec2('Web Audio API')}} 
+ +

Browser Kompatibilität

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(10.0)}}{{property_prefix("webkit")}}{{CompatGeckoDesktop(25.0)}} {{CompatNo}}15.0{{property_prefix("webkit")}}
+ 22
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
+
+ +

Siehe auch

+ + diff --git a/files/de/web/api/gamepad_api/index.html b/files/de/web/api/gamepad_api/index.html new file mode 100644 index 0000000000..d72bf51274 --- /dev/null +++ b/files/de/web/api/gamepad_api/index.html @@ -0,0 +1,95 @@ +--- +title: Gamepad API +slug: Web/API/Gamepad_API +tags: + - API + - Experimentel + - Spiele + - Übersicht +translation_of: Web/API/Gamepad_API +--- +
{{DefaultAPISidebar("Gamepad API")}}
+ +

Die Gamepad API ist ein Weg für  Entwickler auf Eingaben eines Gamepads und anderen Spielsteuergeräte in einer einfachen und konsequenten Weise zuzugreifen und darauf zu reagieren. Es enthält drei Schnittstellen, zwei Ereignisse und eine Spezialfunktion, welche verwendet wird, um auf verbindende und trennende Gamepads zu reagieren, um auf andere Informationen des Gamepads selbst zuzugreifen und welche Knöpfe und andere Kontrollelemente gerade gedrückt werden.

+ +

Schnittstellen

+ +
+
Gamepad
+
Repräsentiert ein Gamepad/Spielsteuergerät, dass mit dem Computer verbunden ist.
+
GamepadButton
+
Repräsentiert einen Knopf auf einem verbundenen Gamepad.
+
GamepadEvent
+
Das Ereignisobjekt, dass Ereignisse auf dem zusammenhängenden Gamepad repräsentativ auslöst.
+
+ +

Experimentelle Gamepad Erweiterungen

+ +
+
GamepadHapticActuator
+
Repräsentiert Hardware im Steuergeräte welche zur Verfügungstellung von haptischen Feedback für den Nutzer (Falls vefügbar) konzipiert worden ist, meistens handelt es sich um Vibrationsmotoren.
+
GamepadPose
+
Repräsentiert die Stellung des Steuergeräts (z.B. Position und Orientierung im dreidimensionalen Raum) im Falle eines WebVR-Steuergeräts.
+
+ +

Siehe unter Experimentelle Erweiterungen der Gamepad Schnittstelle nach Schnittstellen, die den Zugriff auf die oben erwähnten experimentellen Erweiterungen ermöglichen.

+ +

Erweiterungen für anderen Schnittstellen

+ + + +
+
{{domxref("Navigator.getGamepads()")}}
+
Eine Erweiterung für das {{domxref("Navigator")}} Objekt, das ein Array von {{domxref("Gamepad")}} Objeketen zurückschickt, jeweils eines für jedes verbundene Gamepad.
+
+ +

Window Ereignisse

+ +
+
{{domxref("Window.ongamepadconnected")}}
+
Repräsentiert einen Ereignisabwickler, der ausgeführt wird, wenn ein Gamepad verbunden wird (Wenn das {{event('gamepadconnected')}} Ereignis auslöst).
+
{{domxref("Window.ongamepaddisconnected")}}
+
Repräsentiert einen  Ereignisabwickler, der ausgeführt wird, wenn ein Gamepad getrennt wird (Wenn das {{event('gamepaddisconnected')}} Ereignis auslöst).
+
+ +

Einführung und Leitfäden

+ + + +

Spezifikation

+ + + + + + + + + + + + + + + + + + + +
SpezifikationStatusKommentar
{{SpecName("GamepadExtensions")}}{{Spec2("GamepadExtensions")}}Definiert die {{anch("Experimental Gamepad extensions")}}.
{{SpecName("Gamepad", "", "The Gamepad API specification")}}{{Spec2("Gamepad")}}Anfängliche Definition
+ +

Browser Kompatibilität

+ + + +

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

+ +

Siehe weiters

+ + diff --git a/files/de/web/api/geolocation/getcurrentposition/index.html b/files/de/web/api/geolocation/getcurrentposition/index.html new file mode 100644 index 0000000000..52fd968a6b --- /dev/null +++ b/files/de/web/api/geolocation/getcurrentposition/index.html @@ -0,0 +1,88 @@ +--- +title: Geolocation.getCurrentPosition() +slug: Web/API/Geolocation/getCurrentPosition +translation_of: Web/API/Geolocation/getCurrentPosition +--- +
{{securecontext_header}}{{ APIRef("Geolocation API") }}
+ +

Mit der Methode Geolocation.getCurrentPosition() kann die Position des Gerätes bestimmt werden.

+ +

Syntax

+ +
navigator.geolocation.getCurrentPosition(success[, error[, [options]])
+ +

Parameter

+ +
+
success
+
Eine Funktion, die nach erfolgreicher Positionsbestimmung aufgerufen wird. Sie erhält ein Objekt vom Typ {{domxref("GeolocationPosition")}} als Parameter.
+
error {{optional_inline}}
+
Eine Funktion, die im Fehlerfall aufgerufen wird. Sie erhält ein Objekt vom Typ {{domxref("GeolocationPositionError")}} als Parameter.
+
options {{optional_inline}}
+
Ein Objekt vom Typ {{domxref("PositionOptions")}}. Es enthält: +
    +
  • maximumAge: Die Positionsbestimmung darf höchstens diese Zeit in Millisekunden zurückliegen. Falls 0, muss ein aktueller Wert ermittelt werden, falls Infinity, sollte kein aktueller Wert ermittelt werden.
    + Vorgabe: 0.
  • +
  • timeout: Wartezeit in Millisekunden, bis die Positionsbestimmung abgebrochen und, so gegeben, die Funktion error aufgerufen wird. Bei Infinity keine Begrenzung.
    + Vorgabe: Infinity.
  • +
  • enableHighAccuracy: true, um eine genauere Position zu ermitteln, jedoch möglicherweise zu Lasten von Wartezeit und Energieverbrauch.
    + Vorgabe: false.
  • +
+
+
+ +

Beispiel

+ +
var options = {
+  enableHighAccuracy: true,
+  timeout: 5000,
+  maximumAge: 0
+};
+
+function success(pos) {
+  var crd = pos.coords;
+
+  console.log('Your current position is:');
+  console.log(`Latitude : ${crd.latitude}`);
+  console.log(`Longitude: ${crd.longitude}`);
+  console.log(`More or less ${crd.accuracy} meters.`);
+}
+
+function error(err) {
+  console.warn(`ERROR(${err.code}): ${err.message}`);
+}
+
+navigator.geolocation.getCurrentPosition(success, error, options);
+
+ +

Spezifikationen

+ + + + + + + + + + + + + + + + +
SpezifikationStatusKommentar
{{SpecName('Geolocation')}}{{Spec2('Geolocation')}}Erste Spezifikation.
+ +

Browserkompatibilität

+ + + +

{{Compat("api.Geolocation.getCurrentPosition")}}

+ +

Siehe auch

+ + diff --git a/files/de/web/api/geolocation/index.html b/files/de/web/api/geolocation/index.html new file mode 100644 index 0000000000..33c5695d42 --- /dev/null +++ b/files/de/web/api/geolocation/index.html @@ -0,0 +1,71 @@ +--- +title: Geolocation +slug: Web/API/Geolocation +tags: + - API + - Advanced + - Geolocation API + - Interface + - NeedsTranslation + - Reference + - Secure context + - TopicStub +translation_of: Web/API/Geolocation +--- +
{{securecontext_header}}{{APIRef("Geolocation API")}}
+ +

The Geolocation interface represents an object able to programmatically obtain the position of the device. It gives Web content access to the location of the device. This allows a Web site or app to offer customized results based on the user's location.

+ +

An object with this interface is obtained using the {{domxref("navigator.geolocation")}} property implemented by the {{domxref("Navigator")}} object.

+ +
+

Note: For security reasons, when a web page tries to access location information, the user is notified and asked to grant permission. Be aware that each browser has its own policies and methods for requesting this permission.

+
+ +

Properties

+ +

The Geolocation interface neither implements, nor inherits any property.

+ +

Methods

+ +

The Geolocation interface doesn't inherit any method.

+ +
+
{{domxref("Geolocation.getCurrentPosition()")}} {{securecontext_inline}}
+
Determines the device's current location and gives back a {{domxref("GeolocationPosition")}} object with the data.
+
{{domxref("Geolocation.watchPosition()")}} {{securecontext_inline}}
+
Returns a long value representing the newly established callback function to be invoked whenever the device location changes.
+
{{domxref("Geolocation.clearWatch()")}} {{securecontext_inline}}
+
Removes the particular handler previously installed using watchPosition().
+
+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Geolocation', '#geolocation_interface')}}{{Spec2('Geolocation')}}Initial specification.
+ +

Browser compatibility

+ + + +

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

+ +

See also

+ + diff --git a/files/de/web/api/globaleventhandlers/index.html b/files/de/web/api/globaleventhandlers/index.html new file mode 100644 index 0000000000..db5dd7178f --- /dev/null +++ b/files/de/web/api/globaleventhandlers/index.html @@ -0,0 +1,540 @@ +--- +title: GlobalEventHandlers +slug: Web/API/GlobalEventHandlers +tags: + - API + - DOM + - HTML-DOM + - Mixin + - NeedsTranslation + - Reference + - TopicStub +translation_of: Web/API/GlobalEventHandlers +--- +
{{ApiRef("HTML DOM")}}
+ +
Der GlobalEventHandlers Mixin beschreibt die Ereignisbehandler, die mehreren Interfaces gemeinsam sind, wie z.B. {{domxref("HTMLElement")}}, {{domxref("Document")}}, oder {{domxref("Window")}}. Jedes dieser Interfaces kann weitere Ereignisbehandler implementieren.
+ +

GlobalEventHandlers ist ein Mixin und kein Interface und es kann kein Objekt dieses Typs angelegt werden.

+ +

Eigenschaften

+ +

Die Ereignis-Eigenschaften der Form onXYZ werden auf dem {{domxref("GlobalEventHandlers")}}} definiert und durch {{domxref("HTMLElement")}}}, {{domxref("Document")}}, {{domxref("Window")}} und {{domxref("WorkerGlobalScope")}}} für Webworker implementiert.

+ +
+
{{domxref("GlobalEventHandlers.onabort")}}
+
Ist ein {{domxref("EventHandler")}}, der den aufzurufenden Code repräsentiert, wenn das Ereignis {{event("abort")}} ausgelöst wird.
+
{{domxref("GlobalEventHandlers.onblur")}}
+
Ist ein {{domxref("EventHandler")}}, der den aufzurufenden Code repräsentiert, wenn das Ereignis {{event("blur")}} ausgelöst wird.
+
{{domxref("GlobalEventHandlers.onerror")}}
+
Ist ein {{domxref("EventHandler")}}, der den aufzurufenden Code repräsentiert, wenn das Ereignis {{event("focus")}} ausgelöst wird.
+
{{domxref("GlobalEventHandlers.onfocus")}}
+
Ist ein {{domxref("EventHandler")}}, der den aufzurufenden Code repräsentiert, wenn das Ereignis {{event("focus")}} ausgelöst wird.
+
{{domxref("GlobalEventHandlers.oncancel")}}
+
Ist ein {{domxref("EventHandler")}}, der den aufzurufenden Code repräsentiert, wenn das Ereignis {{event("cancel")}} ausgelöst wird.
+
{{domxref("GlobalEventHandlers.oncanplay")}}
+
Ist ein {{domxref("EventHandler")}}, der den aufzurufenden Code repräsentiert, wenn das Ereignis {{event("canplay")}} ausgelöst wird.
+
{{domxref("GlobalEventHandlers.oncanplaythrough")}}
+
Ist ein {{domxref("EventHandler")}}, der den aufzurufenden Code repräsentiert, wenn das Ereignis {{event("canplaythrough")}} ausgelöst wird.
+
{{domxref("GlobalEventHandlers.onchange")}}
+
Ist ein {{domxref("EventHandler")}}, der den aufzurufenden Code repräsentiert, wenn das Ereignis {{event("change")}} ausgelöst wird.
+
{{domxref("GlobalEventHandlers.onclick")}}
+
Ist ein {{domxref("EventHandler")}}, der den aufzurufenden Code repräsentiert, wenn das Ereignis {{event("click")}} ausgelöst wird.
+
{{domxref("GlobalEventHandlers.onclose")}}
+
Ist ein {{domxref("EventHandler")}}, der den aufzurufenden Code repräsentiert, wenn das Ereignis {{event("close")}} ausgelöst wird.
+
{{domxref("GlobalEventHandlers.oncontextmenu")}}
+
Ist ein {{domxref("EventHandler")}}, der den aufzurufenden Code repräsentiert, wenn das Ereignis {{event("contextmenu")}} ausgelöst wird.
+
{{domxref("GlobalEventHandlers.oncuechange")}}
+
Ist ein {{domxref("EventHandler")}}, der den aufzurufenden Code repräsentiert, wenn das Ereignis {{event("cuechange")}} ausgelöst wird.
+
{{domxref("GlobalEventHandlers.ondblclick")}}
+
Ist ein {{domxref("EventHandler")}}}, der den aufzurufenden Code repräsentiert, wenn das Ereignis {{event("dblclick")}} ausgelöst wird.
+
{{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("GlobalEventHandler.onmozfullscreenchange")}} {{non-standard_inline}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("fullscreenchange")}} event is raised.
+
{{domxref("GlobalEventHandler.onmozfullscreenerror")}} {{non-standard_inline}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("fullscreenerror")}} 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/de/web/api/globaleventhandlers/onclick/index.html b/files/de/web/api/globaleventhandlers/onclick/index.html new file mode 100644 index 0000000000..7b71eebd3a --- /dev/null +++ b/files/de/web/api/globaleventhandlers/onclick/index.html @@ -0,0 +1,88 @@ +--- +title: Globaler Eventhandler onclick +slug: Web/API/GlobalEventHandlers/onclick +tags: + - API + - HTML DOM + - Méthode + - Referencen +translation_of: Web/API/GlobalEventHandlers/onclick +--- +
+
{{ ApiRef("HTML DOM") }}
+
+ +
 
+ +

Die onclick Methode gibt den click-Eventhandler des Elementes zurück.

+ +
Note: Wenn man das click-Event zum auslösen einer Aktion benutzt, kann man auch in Erwägung ziehen das man die selbe Aktion auf das keydown-Event legt, das erlaubt den Nutzern ohne Maus oder Touchscreen die Aktion trotzdem auszuführen.
+ +

Syntax

+ +
element.onclick = function;
+
+ +

Anstelle von function wird der Methodenname eingetragen, der meistens etwas mit der Funktion der Methode zu tun hat. Siehe "JavaScript Guide:Functions".

+ +

Das Eventobject besteht aus der spezielen Eventhandlermethode die ein {{domxref("MouseEvent")}} ist.

+ +

Beispiel

+ +
<!DOCTYPE html>
+<html lang="de">
+<head>
+<meta charset="UTF-8" />
+<title>onclick Event Beispiel</title>
+<script>
+function initElement() {
+  var p = document.getElementById("foo");
+  // BEACHTE: showAlert(); oder showAlert(param); wird NICHT funktionieren.
+  // Es muss ein Methodenname und NICHT ein Methodenaufruf sein.
+  p.onclick = showAlert;
+};
+
+function showAlert() {
+  alert("onclick Event erkannt!")
+}
+</script>
+<style>
+#foo {
+  border: solid blue 2px;
+}
+</style>
+</head>
+<body onload="initElement();">
+<span id="foo">Mein Eventelement</span>
+<p>Klicke auf das obenstehende Element</p>
+</body>
+</html>
+
+ +

Oder man benutzt eine anonyme Methode, wie hier:

+ +
p.onclick = function() { alert("onclick Event erkannt!"); };
+
+ +

Bemerkungen

+ +

Dieses Event wird ausgefürt wenn der Benutzer auf das Element klickt. Dieses Event wird nach dem Mousedown- und dem Mouseupevent ausgefürt.

+ +

Nur ein Klickhandler kann zu einem Objekt hinzugefügt werden in dieser Variable gespeichert werden. Man kann auch die {{domxref("EventTarget.addEventListener()")}} Methode benutzen, seit es flexibel ist und teil der DOM Evente Spezifikation.

+ +

Spezifikation

+ + + + + + + + + + + + + + +
SpezifikationStatusKommentar
{{SpecName('HTML WHATWG','webappapis.html#handler-onclick','onclick')}}{{Spec2('HTML WHATWG')}}---
diff --git a/files/de/web/api/globaleventhandlers/onload/index.html b/files/de/web/api/globaleventhandlers/onload/index.html new file mode 100644 index 0000000000..87f61085dd --- /dev/null +++ b/files/de/web/api/globaleventhandlers/onload/index.html @@ -0,0 +1,150 @@ +--- +title: GlobalEventHandlers.onload +slug: Web/API/GlobalEventHandlers/onload +tags: + - API + - Event Handler + - GlobalEventHandlers + - HTML DOM + - Property + - Reference + - onload +translation_of: Web/API/GlobalEventHandlers/onload +--- +
{{ApiRef()}}
+ +
Die onload-Eigenschaft der {{domxref("GlobalEventHandlers")}} ist ein Ereignis-Handler für das load-Ereignis eines {{domxref("Window")}}s, {{domxref("XMLHttpRequest")}}s, {{htmlelement("img")}}-Elements, etc., der aufgerufen wird, wenn die Ressource fertig geladen hat.
+ +

Syntax

+ +
window.onload = funcRef;
+
+ +

Value

+ +

funcRef ist die Handler-Funktion, die aufgerufen wird, wenn das load-Ereignis des Windows eintritt.

+ +

Beispiele

+ +
window.onload = function() {
+  init();
+  etwasAnderesTun();
+};
+
+ +
<!doctype html>
+<html>
+  <head>
+    <title>onload-Test</title>
+    // ES5
+    <script>
+      function load() {
+        console.log("load-Ereignis festgestellt!");
+      }
+      window.onload = load;
+    </script>
+    // ES2015
+    <script>
+      const load = () => {
+        console.log("load-Ereignis festgestellt!");
+      }
+      window.onload = load;
+    </script>
+  </head>
+  <body>
+    <p>Das load-Ereignis tritt ein, wenn das Dokument fertig geladen ist!</p>
+  </body>
+</html>
+
+ +

Anmerkungen

+ +

Das load-Ereignis tritt am Ende des Dokumentladeprozesses ein. An diesem Punkt befinden sich alle Objekte des Dokuments im DOM und alle Grafiken, Skripte, Links und Sub-Frames sind vollständig geladen.

+ +

Es gibt zudem Gecko-spezifische DOM-Ereignisse wie DOMContentLoaded und DOMFrameContentLoaded (welches mit {{domxref("EventTarget.addEventListener()")}} gehandhabt werden kann), die eintreten, nachdem sich der DOM der Seite aufgebaut hat, aber nicht darauf warten, dass andere Ressourcen fertig geladen wurden.

+ +

Spezifikationen

+ + + + + + + + + + + + + + + + +
SpezifikationStatusKommentar
{{SpecName("HTML WHATWG", "webappapis.html#handler-onload", "onload")}}{{Spec2("HTML WHATWG")}}Anfängliche Definition
+ +

Browser-Kompatibilität

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewEdgeFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}
+
+ +

Siehe auch

+ + diff --git a/files/de/web/api/globaleventhandlers/onresize/index.html b/files/de/web/api/globaleventhandlers/onresize/index.html new file mode 100644 index 0000000000..b9866678c3 --- /dev/null +++ b/files/de/web/api/globaleventhandlers/onresize/index.html @@ -0,0 +1,77 @@ +--- +title: GlobalEventHandlers.onresize +slug: Web/API/GlobalEventHandlers/onresize +tags: + - API + - DOM + - Property +translation_of: Web/API/GlobalEventHandlers/onresize +--- +

{{ ApiRef() }}

+ +

Die GlobalEventHandlers.onresize Property enthält einen {{domxref("EventHandler")}}, der ausgelöst wird, sobald ein {{event("resize")}}-Event empfangen wird.

+ +

Syntax

+ +
window.onresize = funcRef;
+
+ +

Parameter

+ + + +

Beispiel

+ +
window.onresize = doFunc;
+
+ +
<html>
+<head>
+
+<title>onresize Test</title>
+
+</head>
+
+<body>
+<p>Verändere die Größe des Browser Fensters, um den resize-Event auszulösen.</p>
+
+<p>Window height: <span id="height"></span></p>
+<p>Window width: <span id="width"></span></p>
+
+<script type="text/javascript">
+  var heightOutput = document.querySelector('#height');
+  var widthOutput = document.querySelector('#width');
+
+  function resize() {
+    heightOutput.textContent = window.innerHeight;
+    widthOutput.textContent = window.innerWidth;
+  }
+
+  window.onresize = resize;
+</script>
+</body>
+</html>
+
+ +

Anmerkung

+ +

Das resize-Event wird ausgelöst nachdem die Größe des Fensters verändert wurde.

+ +

Spezifikation

+ + + + + + + + + + + + + + +
SpezifikationStatusKommentar
{{SpecName('HTML WHATWG','webappapis.html#handler-onresize','onresize')}}{{Spec2('HTML WHATWG')}} 
diff --git a/files/de/web/api/htmlcanvaselement/index.html b/files/de/web/api/htmlcanvaselement/index.html new file mode 100644 index 0000000000..3083824dc8 --- /dev/null +++ b/files/de/web/api/htmlcanvaselement/index.html @@ -0,0 +1,242 @@ +--- +title: HTMLCanvasElement +slug: Web/API/HTMLCanvasElement +tags: + - API + - Canvas + - Graphiken + - WebGL +translation_of: Web/API/HTMLCanvasElement +--- +
+
{{APIRef("Canvas API")}}
+
+ +

Das HTMLCanvasElement interface bietet Eigenschaften und Methoden zum Manipulieren des Layouts und der Darstellung des <canvas>-Elements. Das HTMLCanvasElement interface erbt außerdem Eigenschaften und Methoden des {{domxref("HTMLElement")}} interface.

+ +

Eigenschaften

+ +

Erbt Eigenschaften von seinem Elternelement, {{domxref("HTMLElement")}}.

+ +
+
{{domxref("HTMLCanvasElement.height")}}
+
Ein positiver integer, der das {{htmlattrxref("height", "canvas")}} HTML-Attribut des {{HTMLElement("canvas")}} Elements in CSS-Pixeln repräsentiert. Wenn nicht definiert oder wenn es auf einen nicht erlaubten Wert (z.B. einen negativen Wert) gesetzt wird, wird der Standardwert 150 verwendet.
+
{{domxref("HTMLCanvasElement.mozOpaque")}} {{non-standard_inline}}
+
Ein {{jsxref("Boolean")}}, der das {{htmlattrxref("moz-opaque", "canvas")}} HTML-Attribut des {{HTMLElement("canvas")}} Elements repräsentiert. Es sagt dem canvas, ob auf Transparenz verzichtet werden soll. Falls true, kann das Zeichnen auf dem canvas beschleunigt werden.
+
{{domxref("HTMLCanvasElement.width")}}
+
Ein positiver integer, der das {{htmlattrxref("width", "canvas")}} HTML-Attribut des {{HTMLElement("canvas")}} Elements in CSS-Pixeln anzeigt. Wenn nicht definiert oder wenn es auf einen nicht erlaubten Wert (z.B. einen negativen Wert) gesetzt wird, wird der Standardwert 300 verwendet.
+
+ +

Methoden

+ +

Erbt Eigenschaften von seinem Elternelement, {{domxref("HTMLElement")}}.

+ +
+
{{domxref("HTMLCanvasElement.captureStream()")}} {{experimental_inline}}
+
Gibt ein {{domxref("CanvasCaptureMediaStream")}} zurück, dieses ist ein Echtzeit-Video der Oberfläche des canvas.
+
{{domxref("HTMLCanvasElement.getContext()")}}
+
Gibt einen context des canvas zurück oder null, falls die context-ID nicht unterstützt wird. Ein context ermöglicht es, auf dem canvas zu zeichnen. Der Aufruf dieser Methode mit "2d" gibt ein {{domxref("CanvasRenderingContext2D")}} Objekt zurück, während er mit "experimental-webgl" oder "webgl" ein {{domxref("WebGLRenderingContext")}} Objekt zurückgibt. Dieser context ist nur bei Browsern möglich, die WebGL unterstützen.
+
{{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.
+
+ +

Spezifikationen

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

Browserkompatibilität

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support (2D context)4.0{{CompatGeckoDesktop('1.9.2')}}9.09.0 [1]3.1
toBlob(){{CompatNo}} (bug 67587){{CompatGeckoDesktop('19')}} [2]{{CompatUnknown}}{{CompatUnknown}}{{CompatNo}} (bug 71270)
probablySupportsContext(),
+ setContext(),
+ transferControlToProxy() {{experimental_inline}}
{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
mozGetAsFile() {{non-standard_inline}} {{deprecated_inline}}{{CompatNo}}{{CompatGeckoDesktop('2')}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
captureStream() {{experimental_inline}}{{CompatNo}}{{CompatGeckoDesktop('41')}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
transferControlToOffscreen() {{experimental_inline}}{{CompatNo}}{{CompatGeckoDesktop(44)}} [3]{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support (2D context)2.1{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}10.0 [1]3.2
webgl context{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}} as experimental-webgl{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
toBlob(){{CompatNo}} (bug 67587){{CompatNo}} (bug 67587){{CompatGeckoMobile('18')}} [2]{{CompatUnknown}}{{CompatUnknown}}{{CompatNo}} (bug 71270)
probablySupportsContext(),
+ setContext(),
+ transferControlToProxy() {{experimental_inline}}
{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
mozGetAsFile() {{non-standard_inline}} {{deprecated_inline}}{{CompatNo}}{{CompatNo}}{{CompatGeckoMobile('2')}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
captureStream() {{experimental_inline}}{{CompatNo}}{{CompatNo}}{{CompatGeckoMobile('41')}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
transferControlToOffscreen() {{experimental_inline}}{{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.

+ +

Siehe auch

+ + diff --git a/files/de/web/api/htmlcanvaselement/todataurl/index.html b/files/de/web/api/htmlcanvaselement/todataurl/index.html new file mode 100644 index 0000000000..c0a0a900d4 --- /dev/null +++ b/files/de/web/api/htmlcanvaselement/todataurl/index.html @@ -0,0 +1,206 @@ +--- +title: HTMLCanvasElement.toDataURL() +slug: Web/API/HTMLCanvasElement/toDataURL +tags: + - API + - Canvas + - DataURI erstellen + - HTMLCanvasElement + - Method + - Methode(2) + - Referenz +translation_of: Web/API/HTMLCanvasElement/toDataURL +--- +
+
+
{{APIRef("Canvas API")}}
+
+
+ +

Die HTMLCanvasElement.toDataURL()-Methode gibt eine Repräsentation des Bildes als data URI zurück. Das gewünschte Format wird mit den angegebenen Parametern definiert (standardmäßig PNG). Das zurückgegebene Bild besitzt eine Auflösung von 96 dpi.

+ + + +

Syntax

+ +
canvas.toDataURL(type, encoderOptions);
+
+ +

Parameter

+ +
+
type {{optional_inline}}
+
Ein Parameter vom Typ {{domxref("DOMString")}} bestimmt das Bild-Format. Der Standard type ist image/png.
+
encoderOptions {{optional_inline}}
+
Ein Parameter vom Typ {{jsxref("Number")}} zwischen 0 und 1 gibt die Bildqualität an, wenn der Anfragetyp image/jpeg oder image/webp ist.
+ Wenn das Argument irgend etwas anderes enthält, wird der Standardwert für die Bildqualität verwendet. Der Standardwert liegt bei 0.92. Andere Argumente werden ignoriert.
+
+ +

Rückgabewerte

+ +

Ein Rückgabewert vom Typ {{domxref("DOMString")}} beinhaltet die angefragte data URI.

+ +

Beispiele

+ +

Es ist folgendes {{HTMLElement("canvas")}} Element gegeben:

+ +
<canvas id="canvas" width="5" height="5"></canvas>
+
+ +

Mit den folgenden Zeilen erhalten Sie die data-URL des Canvas:

+ +
var canvas = document.getElementById("canvas");
+var dataURL = canvas.toDataURL();
+console.log(dataURL);
+// "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNby
+// blAAAADElEQVQImWNgoBMAAABpAAFEI8ARAAAAAElFTkSuQmCC"
+
+ +

Die Bildqualität für jpegs einstellen

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

Beispiel: Dynamisches Ändern von Bildern

+ +

Sie können diese Technik in Verbindung mit Maus-Events nutzen, um dynamisch Bilder abzuändern (in diesem Beispiel schwarz-weiß und farbig):

+ +

HTML

+ +
<img class="schwarz-weiss" src="myPicture.png" alt="Beschreibung meines Bildes" />
+ +

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("schwarz-weiss"),
+      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);
+  }
+}
+ +

Spezifikationen

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpezifikationStatusKommentare
{{SpecName('HTML WHATWG', "scripting.html#dom-canvas-todataurl", "HTMLCanvasElement.toDataURL")}}{{Spec2('HTML WHATWG')}}Keine Änderungen seit letztem Schnappschuss, {{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')}}Schnappschuss von {{SpecName('HTML WHATWG')}} beinhaltet ursprüngliche Definition.
+ +

Browser-Kompatiblität

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{ CompatChrome(4) }}{{ CompatGeckoDesktop("1.9.2") }}{{ CompatIE(9) }}{{ CompatOpera(9) }}{{ CompatSafari(4.0) }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{ CompatAndroid(3.2) }}{{ CompatAndroid(18) }}{{ CompatGeckoMobile("1.9.2") }}{{ CompatVersionUnknown() }}{{ CompatOpera(19) }}{{ CompatSafari(3.0) }}
+
+ +

Schauen Sie auch unter

+ + diff --git a/files/de/web/api/htmlcanvaselement/webglcontextcreationerror_event/index.html b/files/de/web/api/htmlcanvaselement/webglcontextcreationerror_event/index.html new file mode 100644 index 0000000000..244bbcc76e --- /dev/null +++ b/files/de/web/api/htmlcanvaselement/webglcontextcreationerror_event/index.html @@ -0,0 +1,132 @@ +--- +title: webglcontextcreationerror +slug: Web/API/HTMLCanvasElement/webglcontextcreationerror_event +tags: + - Event + - WebGL + - WebGLContextEvent +translation_of: Web/API/HTMLCanvasElement/webglcontextcreationerror_event +--- +
{{APIRef}}
+ +
+

Das webglcontextcreationerror Event der WebGL API wird ausgelöst, wenn der User-Agent nicht in der Lage ist einen {{domxref("WebGLRenderingContext")}} zu erzeugen.

+ +

Das Event hat die Eigenschaft {{domxref("WebGLContextEvent.statusMessage")}}, die einen plattformabhängigen String mit weiteren Informationen über den Fehler enthält.

+
+ + + + + + + + + + + + + + + + + + + + +
BubblesJa
CancelableJa
Zielobjekt{{domxref("HTMLCanvasElement")}}
Interface{{domxref("WebGLContextEvent")}}
+ +

Beispiel

+ +
var canvas = document.getElementById("canvas");
+
+canvas.addEventListener("webglcontextcreationerror", function(e) {
+  console.log(e.statusMessage || "Unknown error");
+}, false);
+
+var gl = canvas.getContext("webgl");
+// logs statusMessage or "Unknown error" if unable to create WebGL context
+
+ +

Vererbung

+ +

Das webglcontextcreationerror Event implementiert das {{domxref("WebGLContextEvent")}} Interface, welches die Eigenschaften und Methoden von {{domxref("Event")}} erbt.

+ +

{{InheritanceDiagram('','','', 'WebGLContextEvent')}}

+ +

Spezifikationen

+ + + + + + + + + + + + + + +
SpezifikationStatusHinweis
{{SpecName('WebGL', '#5.15.4', 'webglcontextcreationerror')}}{{Spec2('WebGL')}}Grundlegende Definition.
+ +

Browser-Kompatibilität

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome("9")}}{{CompatGeckoDesktop(49)}}{{CompatIE("11")}}{{CompatOpera("12")}}{{CompatSafari("5.1")}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}25{{CompatGeckoMobile(49)}}{{CompatUnknown}}128
+
+ +

Siehe auch

+ + diff --git a/files/de/web/api/htmlcanvaselement/webglcontextlost_event/index.html b/files/de/web/api/htmlcanvaselement/webglcontextlost_event/index.html new file mode 100644 index 0000000000..786d9e49b9 --- /dev/null +++ b/files/de/web/api/htmlcanvaselement/webglcontextlost_event/index.html @@ -0,0 +1,133 @@ +--- +title: webglcontextlost +slug: Web/API/HTMLCanvasElement/webglcontextlost_event +tags: + - Event + - WebGL + - WebGLContextEvent +translation_of: Web/API/HTMLCanvasElement/webglcontextlost_event +--- +
{{APIRef}}
+ +
+

Das webglcontextlost Event der WebGL API wird ausgelöst, wenn der User-Agent feststellt, dass der mit dem {{domxref("WebGLRenderingContext")}}-Objekt verknüpften Drawing Buffer verloren gegangen ist.

+
+ + + + + + + + + + + + + + + + + + + + +
BubblesJa
CancelableJa
Zielobjekt{{domxref("HTMLCanvasElement")}}
Interface{{domxref("WebGLContextEvent")}}
+ +

Beispiel

+ +

Mit der Hilfe der {{domxref("WEBGL_lose_context")}} Extension kann das webglcontextlost Event simuliert werden:

+ +
var canvas = document.getElementById("canvas");
+var gl = canvas.getContext("webgl");
+
+canvas.addEventListener("webglcontextlost", function(e) {
+  console.log(e);
+}, false);
+
+gl.getExtension('WEBGL_lose_context').loseContext();
+
+// "webglcontextlost" event is logged.
+ +

Vererbung

+ +

Das webglcontextlost Event implementiert das {{domxref("WebGLContextEvent")}} Interface, welches die Eigenschaften und Methoden von {{domxref("Event")}} erbt.

+ +

{{InheritanceDiagram('','','', 'WebGLContextEvent')}}

+ +

Spezifikationen

+ + + + + + + + + + + + + + +
SpezifikationStatusHinweis
{{SpecName('WebGL', '#5.15.2', 'webglcontextlost')}}{{Spec2('WebGL')}}Grundlegende Definition.
+ +

Browser-Kompatibilität

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome("9")}}{{CompatGeckoDesktop("2.0")}}{{CompatIE("11")}}{{CompatOpera("12")}}{{CompatSafari("5.1")}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}25{{CompatGeckoMobile("2.0")}}{{CompatUnknown}}128.0
+
+ +

Siehe auch

+ + diff --git a/files/de/web/api/htmlcanvaselement/webglcontextrestored_event/index.html b/files/de/web/api/htmlcanvaselement/webglcontextrestored_event/index.html new file mode 100644 index 0000000000..fc616cccdd --- /dev/null +++ b/files/de/web/api/htmlcanvaselement/webglcontextrestored_event/index.html @@ -0,0 +1,135 @@ +--- +title: webglcontextrestored +slug: Web/API/HTMLCanvasElement/webglcontextrestored_event +tags: + - Event + - WebGL + - WebGLContextEvent +translation_of: Web/API/HTMLCanvasElement/webglcontextrestored_event +--- +
{{APIRef}}
+ +
+

Das webglcontextrestored Event der WebGL API wird ausgelöst, wenn der User-Agent den Drawing Buffer das  {{domxref("WebGLRenderingContext")}}-Objekts wiederhergestellt hat.

+ +

Wenn der Context wiederhergestellt wurde, sind alle zuvor erzeugten WebGL-Ressourcen wie Texturen und Buffer nicht mehr gültig. Die WebGL-Applikation muss dann neu initalisiert und alle Ressourcen neu erstellt werden.

+
+ + + + + + + + + + + + + + + + + + + + +
BubblesYes
CancelableYes
Zielobjekt{{domxref("HTMLCanvasElement")}}
Interface{{domxref("WebGLContextEvent")}}
+ +

Beispiel

+ +

Mit der Hilfe der {{domxref("WEBGL_lose_context")}} Extension kann das webglcontextrestored Event simuliert werden:

+ +
var canvas = document.getElementById("canvas");
+var gl = canvas.getContext("webgl");
+
+canvas.addEventListener("webglcontextrestored", function(e) {
+  console.log(e);
+}, false);
+
+gl.getExtension('WEBGL_lose_context').restoreContext();
+
+// "webglcontextrestored" event is logged.
+ +

Vererbung

+ +

Das webglcontextrestored Event implementiert das {{domxref("WebGLContextEvent")}} Interface, welches die Eigenschaften und Methoden von {{domxref("Event")}} erbt.

+ +

{{InheritanceDiagram('','','', 'WebGLContextEvent')}}

+ +

Spezifikationen

+ + + + + + + + + + + + + + +
SpezifikationStatusHinweis
{{SpecName('WebGL', '#5.15.3', 'webglcontextrestored')}}{{Spec2('WebGL')}}Grundlegende Definition.
+ +

Browser-Kompatibilität

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome("9")}}{{CompatGeckoDesktop("2.0")}}{{CompatIE("11")}}{{CompatOpera("12")}}{{CompatSafari("5.1")}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}25{{CompatGeckoMobile("2.0")}}{{CompatUnknown}}128.0
+
+ +

Siehe auch

+ + diff --git a/files/de/web/api/htmlcollection/index.html b/files/de/web/api/htmlcollection/index.html new file mode 100644 index 0000000000..b09998b7d4 --- /dev/null +++ b/files/de/web/api/htmlcollection/index.html @@ -0,0 +1,70 @@ +--- +title: HTMLCollection +slug: Web/API/HTMLCollection +translation_of: Web/API/HTMLCollection +--- +

{{APIRef("HTML DOM")}}

+ +

Die HTMLCollection repräsentiert eine generische Sammlung (Array-ähnliches Objekt) an Elementen (in Dokumentreihenfolge) und bietet Methoden und Eigenschaften zur Auswahl dieser aus einer Liste an.

+ +
Notiz: Diese Schnittstelle wird aus historischen Gründen HTMLCollection genannt (vor DOM4 konnten Sammlungen, die diese Schnittstelle implementierten, nur HTML-Elemente als Einträge haben).
+ +

Eine HTMLCollection in der HTML DOM ist live; sie wird automatisch aktualisiert, wenn das zugrundeliegende Dokument verändert wird.

+ +

Eigenschaften

+ +
+
{{domxref("HTMLCollection.length")}} {{readonlyInline}}
+
Gibt die Anzahl der Elemente in der Auflistung zurück.
+
+ +

Methoden

+ +
+
{{domxref("HTMLCollection.item()")}}
+
Gibt den spezifischen Knoten am angegebenen nullbasierten index in die Liste zurück.
+ Gibt null zurück, wenn der index außerhalb des Bereichs ist.
+
{{domxref("HTMLCollection.namedItem()")}}
+
Gibt den spezifischen Knoten, dessen ID oder alternativ dessen Name auf die Zeichenkette (spezifiziert durch name) passt, zurück. Die Übereinstimmung des Namens wird nur als letzte Möglichkeit, nur in HTML, und nur, wenn das referenzierte Element das name Attribut unterstützt, durchgeführt.
+ Gibt null zurück, wenn kein Code des angegebenen Namens existiert.
+
+ +

Verwendung in JavaScript

+ +

HTMLCollection setzt auch seine Member direkt als Eigenschaften von name und index. HTML IDs können Doppelpunkte und Punkte als gültige Zeichen beinhalten, was das Verwenden von Klammern für den Zugriff auf Eigenschaften erfordert. Derzeit erkennt HTMLCollections rein numerische IDs nicht, da sie einen Konflikt mit dem Array-ähnlichen Zugriff verursachen würden, obwohl HTML5 dies erlaubt.

+ +

Zum Beispiel, unter der Annahme, dass es ein <form> Element im Dokument und die id "myForm" ist:

+ +
var elem1, elem2;
+
+// document.forms ist eine HTMLCollection
+
+elem1 = document.forms[0];
+elem2 = document.forms.item(0);
+
+alert(elem1 === elem2); // zeigt: "true"
+
+elem1 = document.forms.myForm;
+elem2 = document.forms.namedItem("myForm");
+
+alert(elem1 === elem2); // zeigt: "true"
+
+elem1 = document.forms["bennantes.Element.mit.Punkten"];
+ +

Browser Kompatibilität

+ +

Verschiedene Browser verhalten sich unterschiedlich, wenn es mehr als ein Element gibt, das auf die Zeichenkette passt, die als ein index (oder namedItems Argument) verwendet wird. Firefox 8 verhält sich wie in DOM 2 and DOM4 angegeben, und gibt das erste passende Element zurück. WebKit Browser und Internet Explorer geben in diesem Fall eine andere HTMLCollection und Opera eine {{domxref("NodeList")}} aller passenden Elemente zurück.

+ +

Spezifikation

+ + + +

Siehe auch

+ + diff --git a/files/de/web/api/htmlformelement/elements/index.html b/files/de/web/api/htmlformelement/elements/index.html new file mode 100644 index 0000000000..e5be5603ac --- /dev/null +++ b/files/de/web/api/htmlformelement/elements/index.html @@ -0,0 +1,46 @@ +--- +title: HTMLFormElement.elements +slug: Web/API/HTMLFormElement/elements +translation_of: Web/API/HTMLFormElement/elements +--- +
+
APIRef("HTML DOM")
+
+ +

Die HTMLFormElement.elements Eigenschaft gibt eine domxref("HTMLFormControlsCollection") ( HTMLVersionInline(4) HTMLCollection) aller im FORM element enthaltenen Formularsteuerelemente zurück, mit Ausnahme von input , die ein type attribute haben von image.

+ +

Sie können auf ein bestimmtes Element zugreifen, indem Sie entweder einen Index oder den Elementnamen oder die ID verwenden.

+ +

Syntax

+ +
nodeList = HTMLFormElement.elements
+
+ +

Beschreibung

+ +
let inputs = document.getElementById("form1").elements;
+let inputByIndex = inputs[2];
+let inputByName = inputs["login"];
+
+ +

Spezifikationen

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
SpecName('HTML WHATWG', '#dom-form-elements', 'HTMLFormElement.elements') Spec2('HTML WHATWG')
SpecName("DOM2 HTML", "html.html#ID-76728479", "HTMLFormElement.elements")Spec2("DOM2 HTML")Initial definition
diff --git a/files/de/web/api/htmlformelement/index.html b/files/de/web/api/htmlformelement/index.html new file mode 100644 index 0000000000..45fbc2e027 --- /dev/null +++ b/files/de/web/api/htmlformelement/index.html @@ -0,0 +1,260 @@ +--- +title: HTMLFormElement +slug: Web/API/HTMLFormElement +tags: + - API + - DOM + - HTML + - Interface + - NeedsTranslation + - Reference + - TopicStub +translation_of: Web/API/HTMLFormElement +--- +
{{APIRef("HTML DOM")}}
+ +

The HTMLFormElement interface provides methods to create and modify {{HTMLElement("form")}} elements.

+ + + +

{{InheritanceDiagram(600,120)}}

+ +

Properties

+ +

This interface also inherits properties from its parent, {{domxref("HTMLElement")}}.

+ +
+
{{domxref("HTMLFormElement.elements")}}{{ReadOnlyInline}}
+
A {{domxref("HTMLFormControlsCollection")}} holding all form controls belonging to this form element.
+
{{domxref("HTMLFormElement.length")}}{{ReadOnlyInline}}
+
A long reflecting  the number of controls in the form.
+
{{domxref("HTMLFormElement.name")}}
+
A {{domxref("DOMString")}} reflecting the value of the form's {{ htmlattrxref("name", "form") }} HTML attribute, containing the name of the form.
+
{{domxref("HTMLFormElement.method")}}
+
A {{domxref("DOMString")}} reflecting the value of the form's {{ htmlattrxref("method", "form") }} HTML attribute, indicating the HTTP method used to submit the form. Only specified values can be set.
+
{{domxref("HTMLFormElement.target")}}
+
A {{domxref("DOMString")}} reflecting the value of the form's {{ htmlattrxref("target", "form") }} HTML attribute, indicating where to display the results received from submitting the form.
+
{{domxref("HTMLFormElement.action")}}
+
A {{domxref("DOMString")}} reflecting the value of the form's {{ htmlattrxref("action", "form") }} HTML attribute, containing the URI of a program that processes the information submitted by the form.
+
{{domxref("HTMLFormElement.encoding")}} or {{domxref("HTMLFormElement.enctype")}}
+
A {{domxref("DOMString")}} reflecting the value of the form's {{ htmlattrxref("enctype", "form") }} HTML attribute, indicating the type of content that is used to transmit the form to the server. Only specified values can be set. The two methods are synonyms.
+
{{domxref("HTMLFormElement.acceptCharset")}}
+
A {{domxref("DOMString")}} reflecting the value of the form's {{ htmlattrxref("accept-charset", "form") }} HTML attribute, representing the character encoding that the server accepts.
+
{{domxref("HTMLFormElement.autocomplete")}}
+
A {{domxref("DOMString")}} reflecting the value of the form's {{ htmlattrxref("autocomplete", "form") }} HTML attribute, indicating whether the controls in this form can have their values automatically populated by the browser.
+
{{domxref("HTMLFormElement.noValidate")}}
+
A {{jsxref("Boolean")}} reflecting the value of the form's  {{ htmlattrxref("novalidate", "form") }} HTML attribute, indicating whether the form should not be validated.
+
+ +

Named inputs are added to their owner form instance as properties, and can overwrite native properties if they share the same name (eg a form with an input named action will have its action property return that input instead of the form's {{ htmlattrxref("action", "form") }} HTML attribute).

+ +

Methods

+ +

This interface also inherits methods from its parent, {{domxref("HTMLElement")}}.

+ +
+
{{domxref("HTMLFormElement.submit()")}}
+
Submits the form to the server.
+
{{domxref("HTMLFormElement.reset()")}}
+
Resets the form to its initial state.
+
{{domxref("HTMLFormElement.checkValidity()")}}
+
Returns true if the element's child controls are subject to constraint validation and satisfy those contraints; returns false if some controls do not satisfy their constraints. Fires an event named {{event("invalid")}} at any control that does not satisfy its constraints; such controls are considered invalid if the event is not canceled. It is up to the programmer to decide how to respond to false.
+
{{domxref("HTMLFormElement.reportValidity()")}}
+
Returns true if the element's child controls satisfy their validation constraints. When false is returned, cancelable {{Event("invalid")}} events are fired for each invalid child and validation problems are reported to the user.
+
{{domxref("HTMLFormElement.requestAutocomplete()")}} {{obsolete_inline}}
+
Triggers a native browser interface to assist the user in completing the fields which have an autofill field name value that is not off or on. The form will receive an event once the user has finished with the interface, the event will either be {{event("autocomplete")}} when the fields have been filled or {{event("autocompleteerror")}} when there was a problem. This method has been removed from Chrome and Firefox — see {{bug(1270740)}} for background information on why.
+
+ +

Examples

+ +

Create a new form element, modify its attributes and submit it:

+ +
var f = document.createElement("form");// Create a form
+document.body.appendChild(f);          // Add it to the document body
+f.action = "/cgi-bin/some.cgi";        // Add action and method attributes
+f.method = "POST"
+f.submit();                            // Call the form's submit method
+
+ +

Extract information from a form element and set some of its attributes:

+ +
<form name="formA" id="formA" action="/cgi-bin/test" method="POST">
+ <p>Click "Info" for form details; "Set" to change settings.</p>
+ <p>
+  <input type="button" value="info" onclick="getFormInfo();">
+  <input type="button" value="set"  onclick="setFormInfo(this.form);">
+  <input type="reset" value="reset"><br>
+  <textarea id="tex" style="height:15em; width:20em"></textarea>
+ </p>
+</form>
+
+<script type="text/javascript">
+  function getFormInfo(){
+    var info;
+    var f = document.forms["formA"]; //Get a reference to the form via id.
+    info = "elements: " + f.elements     + "\n"
+         + "length: "   + f.length       + "\n"
+         + "name: "     + f.name         + "\n"
+         + "charset: "  + f.acceptCharset+ "\n"
+         + "action: "   + f.action       + "\n"
+         + "enctype: "  + f.enctype      + "\n"
+         + "encoding: " + f.encoding     + "\n"
+         + "method: "   + f.method       + "\n"
+         + "target: "   + f.target;
+    document.forms["formA"].elements['tex'].value = info;
+  }
+  function setFormInfo(f){ //Argument is a reference to the form.
+    f.method = "GET";
+    f.action = "/cgi-bin/evil_executable.cgi";
+    f.name   = "totally_new";
+  }
+</script>
+
+ +

Submit a form in a popup window:

+ +
<!doctype html>
+<html>
+<head>
+<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
+<title>MDN Example</title>
+<script type="text/javascript">
+function popupSend (oFormElement) {
+  if (oFormElement.method && oFormElement.method.toLowerCase() !== "get") {
+    console.error("This script supports the GET method only.");
+    return;
+  }
+  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);
+    }
+  }
+  open(oFormElement.action.replace(/(?:\?.*)?$/, sSearch.replace(/^&/, "?")), "submit-" + (oFormElement.name || Math.floor(Math.random() * 1e6)), "resizable=yes,scrollbars=yes,status=yes");
+}
+</script>
+
+</head>
+
+<body>
+
+<form name="yourForm" action="test.php" method="get" onsubmit="popupSend(this); return false;">
+  <p>First name: <input type="text" name="firstname" /><br />
+  Last name: <input type="text" name="lastname" /><br />
+  Password: <input type="password" name="pwd" /><br />
+  <input type="radio" name="sex" value="male" /> Male <input type="radio" name="sex" value="female" /> Female</p>
+  <p><input type="checkbox" name="vehicle" value="Bike" />I have a bike<br />
+  <input type="checkbox" name="vehicle" value="Car" />I have a car</p>
+  <p><input type="submit" value="Submit" /></p>
+</form>
+
+</body>
+</html>
+ +

Submitting forms and uploading files using XMLHttpRequest

+ +

If you want to know how to serialize and submit a form using the {{domxref("XMLHttpRequest")}} API, please read this paragraph.

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "forms.html#the-form-element", "HTMLFormElement")}}{{Spec2('HTML WHATWG')}}The following method has been added: requestAutocomplete().
{{SpecName('HTML5 W3C', "forms.html#the-form-element", "HTMLFormElement")}}{{Spec2('HTML5 W3C')}}The elements properties returns an {{domxref("HTMLFormControlsCollection")}} instead of a raw {{domxref("HTMLCollection")}}. This is mainly a technical change. The following method has been added: checkValidity(). The following properties have been added: autocomplete, noValidate, and encoding.
{{SpecName('DOM2 HTML', 'html.html#ID-40002357', 'HTMLFormElement')}}{{Spec2('DOM2 HTML')}}No change
{{SpecName('DOM1', 'level-one-html.html#ID-40002357', 'HTMLFormElement')}}{{Spec2('DOM1')}}Initial definition
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoDesktop(1.0)}}[1]{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile(1.0)}}[1]{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

[1] In Firefox 56, the implementation has been updated so that the action property returns the correct form submission URL, as per spec ({{bug(1366361)}}).

+ +

See also

+ + diff --git a/files/de/web/api/htmlformelement/submit_event/index.html b/files/de/web/api/htmlformelement/submit_event/index.html new file mode 100644 index 0000000000..722fba4d46 --- /dev/null +++ b/files/de/web/api/htmlformelement/submit_event/index.html @@ -0,0 +1,76 @@ +--- +title: submit +slug: Web/API/HTMLFormElement/submit_event +tags: + - Event + - submit +translation_of: Web/API/HTMLFormElement/submit_event +--- +

Das submit Event tritt ein, wenn ein Formular (<form ...></form>) abgeschickt wird.

+ +

Es gilt zu beachten, dass das submit Event nur auf dem Formularelement ausgelöst wird. Der auslösende <button> oder <input type="submit" ... /> erhalten das Event nicht (Es wird das Formular abgeschickt, nicht der Button).

+ +

Allgemein

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpezifikationHTML5
Interface{{domxref("Event")}}
Propagiert ("Bubbles")Ja (obwohl eigentlich einfach Event ohne Propagation)
CancelableJa
ZielElement
StandardaktionAbhängig von Implementierung (schickt Inhalt des Formulars zum Server)
+ +

Eigenschaften

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
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}}{{jsxref("Boolean")}}Whether the event normally bubbles or not.
cancelable {{readonlyInline}}{{jsxref("Boolean")}}Whether the event is cancellable or not.
diff --git a/files/de/web/api/htmlinputelement/index.html b/files/de/web/api/htmlinputelement/index.html new file mode 100644 index 0000000000..284d3cc770 --- /dev/null +++ b/files/de/web/api/htmlinputelement/index.html @@ -0,0 +1,435 @@ +--- +title: HTMLInputElement +slug: Web/API/HTMLInputElement +tags: + - API + - HTML DOM + - HTMLInputElement + - Input + - Interface + - NeedsContent + - NeedsMarkupWork + - NeedsTranslation + - Reference + - TopicStub +translation_of: Web/API/HTMLInputElement +--- +
{{ APIRef("HTML DOM") }}
+ +

The HTMLInputElement interface provides special properties and methods for manipulating the options, layout, and presentation of {{HtmlElement("input")}} elements.

+ +

{{InheritanceDiagram(600, 120)}}

+ +

Properties

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Properties related to the parent form
form {{readonlyInline}}{{domxref("HTMLFormElement")}} object: Returns a reference to the parent {{HtmlElement("form")}} element.
formActionstring: Returns / Sets the element's {{ htmlattrxref("formaction", "input") }} attribute, containing the URI of a program that processes information submitted by the element. This overrides the {{ htmlattrxref("action", "form") }} attribute of the parent form.
formEncTypestring: Returns / Sets the element's {{ htmlattrxref("formenctype", "input") }} attribute, containing the type of content that is used to submit the form to the server. This overrides the {{ htmlattrxref("enctype", "form") }} attribute of the parent form.
formMethodstring: Returns / Sets the element's {{ htmlattrxref("formmethod", "input") }} attribute, containing the HTTP method that the browser uses to submit the form. This overrides the {{ htmlattrxref("method", "form") }} attribute of the parent form.
formNoValidate{{jsxref("Boolean")}}: Returns / Sets the element's {{ htmlattrxref("formnovalidate", "input") }} attribute, indicating that the form is not to be validated when it is submitted. This overrides the {{ htmlattrxref("novalidate", "form") }} attribute of the parent form.
formTargetstring: Returns / Sets the element's {{ htmlattrxref("formtarget", "input") }} attribute, containing a name or keyword indicating where to display the response that is received after submitting the form. This overrides the {{ htmlattrxref("target", "form") }} attribute of the parent form.
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Properties that apply to any type of input element that is not hidden
namestring: Returns / Sets the element's {{ htmlattrxref("name", "input") }} attribute, containing a name that identifies the element when submitting the form.
typestring: Returns / Sets the element's {{ htmlattrxref("type", "input") }} attribute, indicating the type of control to display. See {{ htmlattrxref("type", "input") }} attribute of {{ HTMLElement("input") }} for possible values.
disabled{{jsxref("Boolean")}}: Returns / Sets the element's {{ htmlattrxref("disabled", "input") }} attribute, indicating that the control is not available for interaction. The input values will not be submitted with the form. See also {{ htmlattrxref("readOnly", "input") }}
autofocus{{jsxref("Boolean")}}: Returns / Sets the element's {{ htmlattrxref("autofocus", "input") }} attribute, which specifies that a form control should have input focus when the page loads, unless the user overrides it, for example by typing in a different control. Only one form element in a document can have the {{htmlattrxref("autofocus","input")}} attribute. It cannot be applied if the {{htmlattrxref("type","input")}} attribute is set to hidden (that is, you cannot automatically set focus to a hidden control).
required{{jsxref("Boolean")}}: Returns / Sets the element's {{ htmlattrxref("required", "input") }} attribute, indicating that the user must fill in a value before submitting a form.
valuestring: Returns / Sets the current value of the control. +

Note: If the user enters a value different from the value expected, this may return an empty string.

+
validity {{readonlyInline}}{{domxref("ValidityState")}} object: Returns the element's current validity state.
validationMessage {{readonlyInline}}string: Returns 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. This value can be set by the setCustomValidity method.
willValidate {{readonlyInline}}{{jsxref("Boolean")}}: Returns whether the element is a candidate for constraint validation. It is false if any conditions bar it from constraint validation, including: its type is hidden, reset, or button; it has a datalist ancestor; its disabled property is true.
+ + + + + + + + + + + + + + + + + +
Properties that apply only to elements of type checkbox or radio
checked{{jsxref("Boolean")}}: Returns / Sets the current state of the element when {{htmlattrxref("type","input")}} is checkbox or radio.
defaultChecked{{jsxref("Boolean")}}: Returns / Sets the default state of a radio button or checkbox as originally specified in HTML that created this object.
indeterminate{{jsxref("Boolean")}}: Returns whether the checkbox or radio button is in indeterminate state. For checkboxes, the effect is that the appearance of the checkbox is obscured/greyed in some way as to indicate its state is indeterminate (not checked but not unchecked). Does not affect the value of the checked attribute, and clicking the checkbox will set the value to false.
+ + + + + + + + + + + + + + + + + + + + + +
Properties that apply only to elements of type image
altstring: Returns / Sets the element's {{ htmlattrxref("alt", "input") }} attribute, containing alternative text to use when {{htmlattrxref("type","input")}} is image.
heightstring: Returns / Sets the element's {{ htmlattrxref("height", "input") }} attribute, which defines the height of the image displayed for the button, if the value of {{htmlattrxref("type","input")}} is image.
srcstring: Returns / Sets the element's {{ htmlattrxref("src", "input") }} attribute, which specifies a URI for the location of an image to display on the graphical submit button, if the value of {{htmlattrxref("type","input")}} is image; otherwise it is ignored.
widthstring: Returns / Sets the document's {{ htmlattrxref("width", "input") }} attribute, which defines the width of the image displayed for the button, if the value of {{htmlattrxref("type","input")}} is image.
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Properties that apply only to elements of type file
acceptstring: Returns / Sets the element's {{ htmlattrxref("accept", "input") }} attribute, containing comma-separated list of file types accepted by the server when {{htmlattrxref("type","input")}} is file.
allowdirs {{non-standard_inline}}{{jsxref("Boolean")}}: Part of the non-standard Directory Upload API; indicates whether or not to allow directories and files both to be selected in the file list. Implemented only in Firefox and is hidden behind a preference.
filesReturns/accepts a {{domxref("FileList")}} object, which contains a list of {{domxref("File")}} objects representing the files selected for upload.
{{domxref("HTMLInputElement.webkitdirectory", "webkitdirectory")}} {{Non-standard_inline}}{{jsxref("Boolean")}}: Returns the {{htmlattrxref("webkitdirectory", "input")}} attribute; if true, the file system picker interface only accepts directories instead of files.
{{domxref("HTMLInputElement.webkitEntries", "webkitEntries")}} {{Non-standard_inline}}Array of {{domxref("FileSystemEntry")}} objects: Describes the currently selected files or directories.
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Properties that apply only to text/number-containing or elements
autocompletestring: Returns / Sets the element's {{htmlattrxref("autocomplete", "input")}} attribute, indicating whether the value of the control can be automatically completed by the browser. Ignored if the value of the {{htmlattrxref("type","input")}} attribute is hidden, checkbox, radio, file, or a button type (button, submit, reset, image). Possible values are:
+ on: the browser can autocomplete the value using previously stored value
+ off: the user must explicity enter a value
maxstring: Returns / Sets the element's {{ htmlattrxref("max", "input") }} attribute, containing the maximum (numeric or date-time) value for this item, which must not be less than its minimum ({{htmlattrxref("min","input")}} attribute) value.
maxLengthlong: Returns / Sets the element's {{ htmlattrxref("maxlength", "input") }} attribute, containing the maximum number of characters (in Unicode code points) that the value can have. (If you set this to a negative number, an exception will be thrown.)
minstring: Returns / Sets the element's {{ htmlattrxref("min", "input") }} attribute, containing the minimum (numeric or date-time) value for this item, which must not be greater than its maximum ({{htmlattrxref("max","input")}} attribute) value.
minLengthlong: Returns / Sets the element's {{ htmlattrxref("minlength", "input") }} attribute, containing the minimum number of characters (in Unicode code points) that the value can have. (If you set this to a negative number, an exception will be thrown.)
patternstring: Returns / Sets the element's {{ htmlattrxref("pattern", "input") }} attribute, containing a regular expression that the control's value is checked against. Use the {{htmlattrxref("title","input")}} attribute to describe the pattern to help the user. This attribute applies when the value of the {{htmlattrxref("type","input")}} attribute is text, search, tel, url or email; otherwise it is ignored.
placeholderstring: Returns / Sets the element's {{ htmlattrxref("placeholder", "input") }} attribute, containing a hint to the user of what can be entered in the control. The placeholder text must not contain carriage returns or line-feeds. This attribute applies when the value of the {{htmlattrxref("type","input")}} attribute is text, search, tel, url or email; otherwise it is ignored.
readOnlyboolean: Returns / Sets the element's {{ htmlattrxref("readonly", "input") }} 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.
sizeunsigned long: Returns / Sets the element's {{ htmlattrxref("size", "input") }} attribute, which contains the visual 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. Applies only when {{htmlattrxref("type","input")}} is set to text, search, tel, url, email, or password; otherwise it is ignored.
+ + + + + + + + + + + + + + + + + +
Properties that apply only to elements with type text/password/search/tel/url/week/month
selectionStartunsigned long: Returns / Sets the beginning index of the selected text. When nothing is selected, this returns the position of the text input cursor (caret) inside of the {{HTMLElement("input")}} element.
selectionEndunsigned long: Returns / Sets the end index of the selected text. When there's no selection, this returns the offset of the character immediately following the current text input cursor position.
selectionDirectionstring: Returns / Sets the direction in which selection occurred. Possible values are:
+ forward if selection was performed in the start-to-end direction of the current locale
+ backward for the opposite direction
+ none if the direction is unknown
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Properties not yet categorized
defaultValuestring: Returns / Sets the default value as originally specified in the HTML that created this object.
dirNamestring: Returns / Sets the directionality of the element.
accessKeystring: Returns a string containing a single character that switches input focus to the control when pressed.
list {{readonlyInline}}{{domxref("HTMLElement")}} object: Returns the element pointed by the {{ htmlattrxref("list", "input") }} attribute. The property may be null if no HTML element found in the same tree.
multiple{{jsxref("Boolean")}}: Returns / Sets the element's {{ htmlattrxref("multiple", "input") }} attribute, indicating whether more than one value is possible (e.g., multiple files).
files{{domxref("FileList")}} array: Returns the list of selected files.
{{domxref("HTMLInputElement.labels")}} {{readonlyInline}}{{domxref("NodeList")}} array: Returns a list of {{ HTMLElement("label") }} elements that are labels for this element.
stepstring: Returns / Sets the element's {{ htmlattrxref("step", "input") }} 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.
valueAsDate{{jsxref("Date")}} object: Returns / Sets the value of the element, interpreted as a date, or null if conversion is not possible.
valueAsNumberdouble: Returns the value of the element, interpreted as one of the following, in order: +
    +
  • A time value
  • +
  • A number
  • +
  • NaN if conversion is impossible
  • +
+
autocapitalize {{experimental_inline}}string: Defines the capitalization behavior for user input. Valid values are none, off, characters, words, or sentences.
inputmodeProvides a hint to browsers as to the type of virtual keyboard configuration to use when editing this element or its contents.
+ +
+
{{domxref("HTMLInputElement.align")}} {{obsolete_inline}}
+
string: Represents the alignment of the element. Use CSS instead.
+
{{domxref("HTMLInputElement.useMap")}} {{ obsolete_inline }}
+
string: Represents a client-side image map.
+
+ +

Methods

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
{{domxref("HTMLElement.blur()", "blur()")}}Removes focus from the input element; keystrokes will subsequently go nowhere.
{{domxref("HTMLElement.click()", "click()")}}Simulates a click on the input element.
{{domxref("HTMLElement.focus()", "focus()")}}Focuses on the input element; keystrokes will subsequently go to this element.
{{domxref("HTMLInputElement.select()", "select()")}}Selects all the text in the input element, and focuses it so the user can subsequently replace all of its content.
{{domxref("HTMLInputElement.setSelectionRange()", "setSelectionRange()")}}Selects a range of text in the input element (but does not focus it).
{{domxref("HTMLInputElement.setRangeText()", "setRangeText()")}}Replaces a range of text in the input element with new text.
setCustomValidity()Sets a custom validity message for the element. If this message is not the empty string, then the element is suffering from a custom validity error, and does not validate.
checkValidity()Returns a {{jsxref("Boolean")}} that is 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.
reportValidity()Runs the checkValidity() method, and if it returns false (for an invalid input or no pattern attribute provided), then it reports to the user that the input is invalid in the same manner as if you submitted a form.
+ +
+
{{domxref("HTMLInputElement.stepDown()")}}
+
Decrements 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")}}.
  • +
+
+
{{domxref("HTMLInputElement.stepUp()")}}
+
Increments 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")}}.
  • +
+
+
{{domxref("HTMLInputElement.mozSetFileArray()")}} {{non-standard_inline}}
+
Sets the files selected on the input to the given array of {{domxref("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.
+
{{domxref("HTMLInputElement.mozGetFileNameArray()")}} {{non-standard_inline}}
+
Returns an array of all the file names from the input.
+
{{domxref("HTMLInputElement.mozSetFileNameArray()")}} {{non-standard_inline}}
+
Sets the filenames for the files selected on the input. Not for use in frame scripts, because it accesses the file system.
+
+ +

Events

+ +

Listen to these events using addEventListener() or by assigning an event listener to the oneventname property of this interface:

+ +
+
input
+
Fires when the value of an {{HTMLElement("input")}}, {{HTMLElement("select")}}, or {{HTMLElement("textarea")}} element has been changed. Note that this is actually fired on the {{domxref("HTMLElement")}} interface and also applies to contenteditable elements, but we've listed it here because it is most commonly used with form input elements.
+ Also available via the oninput event handler property.
+
invalid
+
Fired when an element does not satisfy its constraints during constraint validation.
+ Also available via the oninvalid event handler property.
+
search
+
Fired when a search is initiated on an {{HTMLElement("input")}} of type="search".
+ Also available via the onsearch event handler property.
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "#htmlinputelement", "HTMLInputElement")}}{{Spec2('HTML WHATWG')}}
{{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

+ +
+ + +

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

+
+ +

See also

+ + diff --git a/files/de/web/api/htmlinputelement/select/index.html b/files/de/web/api/htmlinputelement/select/index.html new file mode 100644 index 0000000000..14354e31dc --- /dev/null +++ b/files/de/web/api/htmlinputelement/select/index.html @@ -0,0 +1,84 @@ +--- +title: HTMLInputElement.select() +slug: Web/API/HTMLInputElement/select +tags: + - Auswählen + - HTML + - JavaScript + - Méthode +translation_of: Web/API/HTMLInputElement/select +--- +
{{ APIRef("HTML DOM") }}
+ +

Die HTMLInputElement.select() Methode selektiert den gesamten Text innerhalb eines {{HTMLElement("textarea")}} oder innerhalb eines {{HTMLElement("input")}} Elements welches ein Textfeld enthält.

+ +

Syntax

+ +
element.select();
+ +

Beispiel

+ +

Klick in diesem Beispiel auf den Button um den gesamten Text innerhalb des <input> Elements zu selektieren.

+ +

HTML

+ +
<input type="text" id="text-box" size="20" value="Hallo Welt!">
+<button onclick="selectText()">Text auswählen</button>
+
+ +

JavaScript

+ +
function selectText() {
+  const input = document.getElementById('text-box');
+  input.focus();
+  input.select();
+}
+ +

Ergebnis

+ +

{{EmbedLiveSample("Beispiel")}}

+ +

Anmerkungen

+ +

Die Methode element.select() fokussiert den Input nicht zwingend, weshalb es oft zusammen mit {{domxref("HTMLElement.focus()")}} verwendet wird.

+ +

In Browsern in denen es nicht unterstützt wird ist es möglich es mit HTMLInputElement.setSelectionRange() (mit den Parametern 0 und der Länge des Werts des Inputs) zu ersetzen.

+ +
<input onClick="this.select();" value="Beispieltext" />
+<!-- gleichbedeutend mit -->
+<input onClick="this.setSelectionRange(0, this.value.length);" value="Beispieltext" />
+
+ +

Spezifikationen

+ + + + + + + + + + + + + + + + +
SpezifikationStatusKommentar
{{SpecName('HTML WHATWG', 'forms.html#dom-textarea/input-select', 'select')}}{{Spec2('HTML WHATWG')}}
+ +

Browser Kompatibilität

+ + + +

{{Compat("api.HTMLInputElement.select")}}

+ +

Siehe auch

+ + diff --git a/files/de/web/api/htmlslotelement/assignednodes/index.html b/files/de/web/api/htmlslotelement/assignednodes/index.html new file mode 100644 index 0000000000..77ab2aef3d --- /dev/null +++ b/files/de/web/api/htmlslotelement/assignednodes/index.html @@ -0,0 +1,66 @@ +--- +title: HTMLSlotElement.assignedNodes() +slug: Web/API/HTMLSlotElement/assignedNodes +translation_of: Web/API/HTMLSlotElement/assignedNodes +--- +

{{APIRef("Shadow DOM API")}}

+ +

Die Eigenschaft assignedNodes() der Schnittstelle {{domxref("HTMLSlotElement")}} gibt die Reihenfolge der diesem Slot zugewiesenen Elemente oder alternativ den Fallback-Inhalt des Slots zurück.

+ +

Syntax

+ +
var assignedNodes[] = HTMLSlotElement.assignedNodes([options])
+ +

Parameter

+ +
+
options {{optional_inline}}
+
Ein Objekt, das Optionen für die zurückzugebenden Knoten festlegt. Die verfügbaren Optionen sind: +
    +
  • flatten: Ein {{jsxref('Boolean')}}, das angibt, ob die dem Slot zugewiesenen Elemente zurückgegeben werden sollen (wenn dieser Wert false ist) oder der Fallback-Inhalt des Slots (wenn dieser Wert true ist). Die Vorgabe ist false.
  • +
+
+
+ +

Rückgabewerte

+ +

Ein Array von Knoten.

+ +

Beispiele

+ +

Das folgende Schnippsel ist unserem Slotchange-Beispiel entnommen (siehe auch live).

+ +
let slots = this.shadowRoot.querySelectorAll('slot');
+slots[1].addEventListener('slotchange', function(e) {
+  let nodes = slots[1].assignedNodes();
+  console.log('Element in Slot "' + slots[1].name + '" changed to "' + nodes[0].outerHTML + '".');
+});
+ +

Hier nehmen wir Verweise auf alle Slots und fügen dann einen Slotchange Event Listener zum zweiten Slot in der Vorlage hinzu - derjenige, dessen Inhalt im Beispiel geändert wird.

+ +

Jedes Mal, wenn sich das in den Slot eingefügte Element ändert, protokollieren wir einen Bericht an die Konsole, aus dem hervorgeht, welcher Slot sich geändert hat und was der neue Knoten im Slot ist.

+ +

Spezifikationen

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG','scripting.html#dom-slot-assignednodes','assignedNodes')}}{{Spec2('HTML WHATWG')}} 
+ +

Browser Kompatibilität

+ +
+ + +

{{Compat("api.HTMLSlotElement.assignedNodes")}}

+
diff --git a/files/de/web/api/htmlslotelement/index.html b/files/de/web/api/htmlslotelement/index.html new file mode 100644 index 0000000000..2644171f01 --- /dev/null +++ b/files/de/web/api/htmlslotelement/index.html @@ -0,0 +1,67 @@ +--- +title: HTMLSlotElement +slug: Web/API/HTMLSlotElement +tags: + - API + - HTMLSlotElement + - Interface + - NeedsTranslation + - Reference + - TopicStub + - shadow dom +translation_of: Web/API/HTMLSlotElement +--- +

{{APIRef('Web Components')}}

+ +

The HTMLSlotElement interface of the Shadow DOM API enables access to the name and assigned nodes of an HTML {{HTMLElement("slot")}} element.

+ +

Properties

+ +
+
{{domxref('HTMLSlotElement.name')}}
+
{{domxref("DOMString")}}: Can be used to get and set the slot's name.
+
+ +

Methods

+ +
+
{{domxref('HTMLSlotElement.assignedNodes()')}}
+
Returns the sequence of elements assigned to this slot, or alternatively the slot's fallback content.
+
+ +

Examples

+ +

The following snippet is taken from our slotchange example (see it live also).

+ +
let slots = this.shadowRoot.querySelectorAll('slot');
+slots[1].addEventListener('slotchange', function(e) {
+  let nodes = slots[1].assignedNodes();
+  console.log('Element in Slot "' + slots[1].name + '" changed to "' + nodes[0].outerHTML + '".');
+});
+ +

Here we grab references to all the slots, then add a slotchange event listener to the 2nd slot in the template — which is the one that keeps having its contents changed in the example.

+ +

Every time the element inserted in the slot changes, we log a report to the console saying which slot has changed, and what the new node inside the slot is.

+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG','scripting.html#htmlslotelement','HTMLSlotElement')}}{{Spec2('HTML WHATWG')}} 
+ +

Browser compatibility

+ + + +

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

diff --git a/files/de/web/api/htmltableelement/createcaption/index.html b/files/de/web/api/htmltableelement/createcaption/index.html new file mode 100644 index 0000000000..fb27bd6480 --- /dev/null +++ b/files/de/web/api/htmltableelement/createcaption/index.html @@ -0,0 +1,75 @@ +--- +title: HTMLTableElement.createCaption() +slug: Web/API/HTMLTableElement/createCaption +tags: + - API + - DOM + - HTML DOM + - HTMLTableElement + - Method + - Reference +translation_of: Web/API/HTMLTableElement/createCaption +--- +
{{APIRef("HTML DOM")}}
+ +

Die HTMLTableElement.createCaption() Methode gibt das {{HtmlElement("caption")}} Element zurück, das einer {{HtmlElement("table")}} zugeordnet ist. Wenn in der Tabelle noch kein <caption> Element existiert, wird es durch diese Methode erzeugt und dann zurückgegeben..

+ +
+

Anmerkung: Wenn noch keine Überschrift vorhanden ist, fügt createCaption() sie direkt in die Tabelle ein. Die Überschrift muss nicht eigens hinzugefügt werden, wie man es tun müsste, wenn man das <caption> Element mittels {{domxref("Document.createElement()")}} erzeugt hätte.

+
+ +

Syntax

+ +
HTMLTableCaptionElement = table.createCaption();
+ +

Rückgabewert

+ +

{{domxref("HTMLTableCaptionElement")}}

+ +

Beispiel

+ +

Dieses Beispiel verwendet JavaScript, um eine Tabelle um eine Überschrift zu erweitern.

+ +

HTML

+ +
<table>
+  <tr><td>Cell 1.1</td><td>Cell 1.2</td><td>Cell 1.3</td></tr>
+  <tr><td>Cell 2.1</td><td>Cell 2.2</td><td>Cell 2.3</td></tr>
+</table>
+ +

JavaScript

+ +
let table = document.querySelector('table');
+let caption = table.createCaption();
+caption.textContent = 'Diese Überschrift wurde mit JavaScript erzeugt!';
+ +

Ergebnis

+ +

{{EmbedLiveSample("Beispiel")}}

+ +

Spezifikationen

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#dom-table-createcaption', 'HTMLTableElement: createCaption')}}{{Spec2('HTML WHATWG')}}
+ +

Browserkompatibilität

+ +
+ + +

{{Compat("api.HTMLTableElement.createCaption")}}

+
diff --git a/files/de/web/api/htmltableelement/index.html b/files/de/web/api/htmltableelement/index.html new file mode 100644 index 0000000000..696556f62f --- /dev/null +++ b/files/de/web/api/htmltableelement/index.html @@ -0,0 +1,132 @@ +--- +title: HTMLTableElement +slug: Web/API/HTMLTableElement +tags: + - API + - HTML DOM + - Interface + - NeedsTranslation + - Reference + - TopicStub +translation_of: Web/API/HTMLTableElement +--- +

{{APIRef("HTML DOM")}}

+ +

The HTMLTableElement interface provides special properties and methods (beyond the regular {{DOMxRef("HTMLElement")}} object interface it also has available to it by inheritance) for manipulating the layout and presentation of tables in an HTML document.

+ +

{{InheritanceDiagram(600, 120)}}

+ +

Properties

+ +

Inherits properties from its parent, {{DOMxRef("HTMLElement")}}.

+ +
+
{{DOMxRef("HTMLTableElement.caption")}}
+
Is a {{DOMxRef("HTMLTableCaptionElement")}} representing the first {{HTMLElement("caption")}} that is a child of the element, or null if none is found. When set, if the object doesn't represent a <caption>, a {{DOMxRef("DOMException")}} with the HierarchyRequestError name is thrown. If a correct object is given, it is inserted in the tree as the first child of this element and the first <caption> that is a child of this element is removed from the tree, if any.
+
{{DOMxRef("HTMLTableElement.tHead")}}
+
Is a {{DOMxRef("HTMLTableSectionElement")}} representing the first {{HTMLElement("thead")}} that is a child of the element, or null if none is found. When set, if the object doesn't represent a <thead>, a {{DOMxRef("DOMException")}} with the HierarchyRequestError name is thrown. If a correct object is given, it is inserted in the tree immediately before the first element that is neither a {{HTMLElement("caption")}}, nor a {{HTMLElement("colgroup")}}, or as the last child if there is no such element, and the first <thead> that is a child of this element is removed from the tree, if any.
+
{{DOMxRef("HTMLTableElement.tFoot")}}
+
Is a {{DOMxRef("HTMLTableSectionElement")}} representing the first {{HTMLElement("tfoot")}} that is a child of the element, or null if none is found. When set, if the object doesn't represent a <tfoot>, a {{DOMxRef("DOMException")}} with the HierarchyRequestError name is thrown. If a correct object is given, it is inserted in the tree immediately before the first element that is neither a {{HTMLElement("caption")}}, a {{HTMLElement("colgroup")}}, nor a {{HTMLElement("thead")}}, or as the last child if there is no such element, and the first <tfoot> that is a child of this element is removed from the tree, if any.
+
{{DOMxRef("HTMLTableElement.rows")}}{{ReadOnlyInline}}
+
Returns a live {{DOMxRef("HTMLCollection")}} containing all the rows of the element, that is all {{HTMLElement("tr")}} that are a child of the element, or a child of one of its {{HTMLElement("thead")}}, {{HTMLElement("tbody")}} and {{HTMLElement("tfoot")}} children. The rows members of a <thead> appear first, in tree order, and those members of a <tbody> last, also in tree order. The HTMLCollection is live and is automatically updated when the HTMLTableElement changes.
+
{{DOMxRef("HTMLTableElement.tBodies")}}{{ReadOnlyInline}}
+
Returns a live {{DOMxRef("HTMLCollection")}} containing all the {{HTMLElement("tbody")}} of the element. The HTMLCollection is live and is automatically updated when the HTMLTableElement changes.
+
+ +

Obsolete Properties

+ +
+

Warning: The following properties are obsolete.  You should avoid using them.

+
+ +
+
+
{{DOMxRef("HTMLTableElement.align")}} {{Obsolete_Inline}}
+
Is a {{DOMxRef("DOMString")}} containing an enumerated value reflecting the {{HTMLAttrxRef("align", "table")}} attribute. It indicates the alignment of the element's contents with respect to the surrounding context. The possible values are "left", "right", and "center".
+
{{DOMxRef("HTMLTableElement.bgColor")}} {{Obsolete_Inline}}
+
Is a {{DOMxRef("DOMString")}} containing the background color of the cells. It reflects the obsolete {{HTMLAttrxRef("bgColor", "table")}} attribute.
+
{{DOMxRef("HTMLTableElement.border")}} {{Obsolete_Inline}}
+
Is a {{DOMxRef("DOMString")}} containing the width in pixels of the border of the table. It reflects the obsolete {{HTMLAttrxRef("border", "table")}} attribute.
+
{{DOMxRef("HTMLTableElement.cellPadding")}} {{Obsolete_Inline}}
+
Is a {{DOMxRef("DOMString")}} containing the width in pixels of the horizontal and vertical sapce between cell content and cell borders. It reflects the obsolete {{HTMLAttrxRef("cellpadding", "table")}} attribute.
+
{{DOMxRef("HTMLTableElement.cellSpacing")}} {{Obsolete_Inline}}
+
Is a {{DOMxRef("DOMString")}} containing the width in pixels of the horizontal and vertical separation between cells. It reflects the obsolete {{HTMLAttrxRef("cellspacing", "table")}} attribute.
+
{{DOMxRef("HTMLTableElement.frame")}} {{Obsolete_Inline}}
+
Is a {{DOMxRef("DOMString")}} containing the type of the external borders of the table. It reflects the obsolete {{HTMLAttrxRef("frame", "table")}} attribute and can take one of the following values: "void", "above", "below", "hsides", "vsides", "lhs", "rhs", "box", or "border".
+
{{DOMxRef("HTMLTableElement.rules")}} {{Obsolete_Inline}}
+
Is a {{DOMxRef("DOMString")}} containing the type of the internal borders of the table. It reflects the obsolete {{HTMLAttrxRef("rules", "table")}} attribute and can take one of the following values: "none", "groups", "rows", "cols", or "all".
+
{{DOMxRef("HTMLTableElement.summary")}} {{Obsolete_Inline}}
+
Is a {{DOMxRef("DOMString")}} containing a description of the purpose or the structure of the table. It reflects the obsolete {{HTMLAttrxRef("summary", "table")}} attribute.
+
{{DOMxRef("HTMLTableElement.width")}} {{Obsolete_Inline}}
+
Is a {{DOMxRef("DOMString")}} containing the length in pixels or in percentage of the desired width fo the entire table. It reflects the obsolete {{HTMLAttrxRef("width", "table")}} attribute.
+
+
+ +

Methods

+ +

Inherits methods from its parent, {{DOMxRef("HTMLElement")}}.

+ +
+
{{DOMxRef("HTMLTableElement.createTHead()")}}
+
Returns an {{DOMxRef("HTMLElement")}} representing the first {{HTMLElement("thead")}} that is a child of the element. If none is found, a new one is created and inserted in the tree immediately before the first element that is neither a {{HTMLElement("caption")}}, nor a {{HTMLElement("colgroup")}}, or as the last child if there is no such element.
+
{{DOMxRef("HTMLTableElement.deleteTHead()")}}
+
Removes the first {{HTMLElement("thead")}} that is a child of the element.
+
{{DOMxRef("HTMLTableElement.createTFoot()")}}
+
Returns an {{DOMxRef("HTMLElement")}} representing the first {{HTMLElement("tfoot")}} that is a child of the element. If none is found, a new one is created and inserted in the tree immediately before the first element that is neither a {{HTMLElement("caption")}}, a {{HTMLElement("colgroup")}}, nor a {{HTMLElement("thead")}}, or as the last child if there is no such element.
+
{{DOMxRef("HTMLTableElement.deleteTFoot()")}}
+
Removes the first {{HTMLElement("tfoot")}} that is a child of the element.
+
{{DOMxRef("HTMLTableElement.createCaption()")}}
+
Returns an {{DOMxRef("HTMLElement")}} representing the first {{HTMLElement("caption")}} that is a child of the element. If none is found, a new one is created and inserted in the tree as the first child of the {{HTMLElement("table")}} element.
+
{{DOMxRef("HTMLTableElement.deleteCaption()")}}
+
Removes the first {{HTMLElement("caption")}} that is a child of the element.
+
{{DOMxRef("HTMLTableElement.insertRow()")}}
+
Returns an {{DOMxRef("HTMLTableRowElement")}} representing a new row of the table. It inserts it in the rows collection immediately before the {{HTMLElement("tr")}} element at the given index position. If necessary a {{HTMLElement("tbody")}} is created. If the index is -1, the new row is appended to the collection. If the index is smaller than -1 or greater than the number of rows in the collection, a {{DOMxRef("DOMException")}} with the value IndexSizeError is raised.
+
{{DOMxRef("HTMLTableElement.deleteRow()")}}
+
Removes the row corresponding to the index given in parameter. If the index value is -1 the last row is removed; if it smaller than -1 or greater than the amount of rows in the collection, a {{DOMxRef("DOMException")}} with the value IndexSizeError is raised.
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "#htmltableelement", "HTMLTableElement")}}{{Spec2('HTML WHATWG')}}Added the sortable property and the stopSorting() method.
{{SpecName('HTML5 W3C', "tabular-data.html#the-table-element", "HTMLTableElement")}}{{Spec2('HTML5 W3C')}}Added the createTBody() method.
{{SpecName('DOM2 HTML', 'html.html#ID-64060425', 'HTMLTableElement')}}{{Spec2('DOM2 HTML')}}Defined when caption, tHead, tFoot, insertRow(), and deleteRow() raise exceptions.
{{SpecName('DOM1', 'level-one-html.html#ID-64060425', 'HTMLTableElement')}}{{Spec2('DOM1')}}Initial definition.
+ +

Browser compatibility

+ + + +

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

+ +

See also

+ + diff --git a/files/de/web/api/htmltableelement/insertrow/index.html b/files/de/web/api/htmltableelement/insertrow/index.html new file mode 100644 index 0000000000..869d185b98 --- /dev/null +++ b/files/de/web/api/htmltableelement/insertrow/index.html @@ -0,0 +1,122 @@ +--- +title: HTMLTableElement.insertRow() +slug: Web/API/HTMLTableElement/insertRow +tags: + - API + - HTML DOM + - HTMLTableElement + - Method + - Reference +translation_of: Web/API/HTMLTableElement/insertRow +--- +
{{APIRef("HTML DOM")}}
+ +

Die Methode HTMLTableElement.insertRow() fügt einer vorhandenen {{HtmlElement("table")}} eine neue Zeile ({{HtmlElement("tr")}}) hinzu und gibt eine Referenz auf die neue Zeile zurück.

+ +

Wenn eine Tabelle mehrere {{HtmlElement("tbody")}} Elemente besitzt, wird die neue Zeile standardmäßig dem letzten <tbody> hinzugefügt. Um sie einem bestimmten <tbody> Element hinzuzufügen, beschaffen Sie sich eine Referenz auf das gewünschte <tbody> Element und rufen Sie insertRow() auf diesem Element auf:

+ +
let bestimmter_tbody = document.getElementById(tbody_id);
+let zeile = bestimmter_tbody.insertRow(index)
+ + + +
+

Anmerkung: insertRow() fügt die Zeile direkt in die Tabelle ein. Die Zeile muss nicht eigens hinzugefügt werden, wie man es tun müsste, wenn man das <tr> Element mittels Document.createElement() erzeugt hätte.

+
+ +

Syntax

+ +
var neueZeile = HTMLTableElement.insertRow(index);
+ +

{{domxref("HTMLTableElement")}} ist eine Referenz auf ein HTML {{HtmlElement("table")}} Element.

+ +

Parameters

+ +
+
index {{optional_inline}}
+
Der Zeilenindex der neuen Zeile. Ist der Index -1 or gleich der Anzahl der vorhandenen Zeilen, wird die Zeile als letzte Zeile angefügt. Wenn index größer als die Anzahl vorhandener Zeilen ist, führt dies zi einer IndexSizeError Exception. Wird index weggelassen, ist der Standardwert -1.
+
+ +

Rückgabewert

+ +

neueZeile ist ein {{domxref("HTMLTableRowElement")}}, das die neue Zeile referenziert.

+ +

Beispiel

+ +

Dieses Beispiel verwendet insertRow(-1), um an eine Tabelle eine neue Zeile anzufügen.

+ +

Wir verwenden daraufhin {{domxref("HTMLTableRowElement.insertCell()")}}, um der neuen Zeile noch eine Zelle hinzufügen. (Um gültiges HTML zu sein, muss ein <tr> mindestens ein <td> Element enthalten.) Schließlich fügen wir der Zelle mittels {{domxref("Document.createTextNode()")}} und {{domxref("Node.appendChild()")}} Text hinzu.

+ +

HTML

+ +
<table id="my-table">
+  <tr><td>Row 1</td></tr>
+  <tr><td>Row 2</td></tr>
+  <tr><td>Row 3</td></tr>
+</table>
+ +

JavaScript

+ +
function addRow(tableID) {
+  // Beschaffe eine Referenz auf die Tabelle
+  let tableRef = document.getElementById(tableID);
+
+  // Füge am Ende der Tabelle eine neue Zeile an
+  let newRow = tableRef.insertRow(-1);
+
+  // Erstelle in der Zeile eine Zelle am Index 0
+  let newCell = newRow.insertCell(0);
+
+  // Füge der Zelle einen textnode hinzu
+  let newText = document.createTextNode('Neue letzte Zeile');
+  newCell.appendChild(newText);
+}
+
+// Rufe addRow() mit der ID der Tabelle auf
+addRow('my-table');
+ +

Result

+ +

{{EmbedLiveSample("Beispiel")}}

+ +

Spezifikationen

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("HTML WHATWG", "tables.html#dom-table-insertrow", "HTMLTableElement.insertRow()")}}{{Spec2("HTML WHATWG")}}
{{SpecName("DOM2 HTML", "html.html#ID-93995626", "HTMLTableElement.insertRow()")}}{{Spec2("DOM2 HTML")}}Spezifiziert genauer, wo die Zeile eingefügt wird.
{{SpecName("DOM1", "level-one-html.html#ID-39872903", "HTMLTableElement.insertRow()")}}{{Spec2("DOM1")}}Initiale Definition
+ +

Browser compatibility

+ +
+ + +

{{Compat("api.HTMLTableElement.insertRow")}}

+
+ +

See also

+ + diff --git a/files/de/web/api/htmlunknownelement/index.html b/files/de/web/api/htmlunknownelement/index.html new file mode 100644 index 0000000000..d1f6107473 --- /dev/null +++ b/files/de/web/api/htmlunknownelement/index.html @@ -0,0 +1,56 @@ +--- +title: HTMLUnknownElement +slug: Web/API/HTMLUnknownElement +translation_of: Web/API/HTMLUnknownElement +--- +

{{APIRef("HTML DOM")}}

+ +

Die Schnittstelle HTMLUnknownElement stellt ein ungültiges HTML-Element dar und leitet sich von der Schnittstelle {{DOMxRef("HTMLElement")}} ab, ohne jedoch zusätzliche Eigenschaften oder Methoden zu implementieren.

+ +

{{InheritanceDiagram(600, 120)}}

+ +

Eigenschaften

+ +

Keine spezifische Eigenschaft; erbt Eigenschaften von seinem übergeordneten Element, {{DOMxRef("HTMLElement")}}.

+ +

Methoden

+ +

Keine spezifische Methode; erbt Eigenschaften von seinem übergeordneten Element, {{DOMxRef("HTMLElement")}}.

+ +

Spezifikationen

+ + + + + + + + + + + + + + + + + + + +
SpezifikationenStatusKommentar
{{SpecName("HTML WHATWG", "elements.html#htmlunknownelement", "HTMLUnknownElement")}}{{Spec2("HTML WHATWG")}}Keine Änderung von {{SpecName("HTML5 W3C")}}.
{{SpecName("HTML5 W3C", "dom.html#htmlunknownelement", "HTMLUnknownElement")}}{{Spec2("HTML5 W3C")}}Erstdefinition.
+ +
+

Browser-Kompatibilität

+
+ + + +

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

+ +

Siehe auch

+ + diff --git a/files/de/web/api/index.html b/files/de/web/api/index.html new file mode 100644 index 0000000000..3173fac5cf --- /dev/null +++ b/files/de/web/api/index.html @@ -0,0 +1,14 @@ +--- +title: Web API Referenz +slug: Web/API +tags: + - API + - DOM + - JavaScript + - Reference + - Web +translation_of: Web/API +--- +

Javascript bietet eine große Auswahl an hervorragenden Schnittstellen (APIs). Nachfolgend findet sich eine Liste aller APIs auf die Du zurückgreifen kannst, um deine Webapp oder Webseite zu programmieren.

+ +
{{APIListAlpha}}
diff --git a/files/de/web/api/indexeddb_api/browser_storage_limits_and_eviction_criteria/index.html b/files/de/web/api/indexeddb_api/browser_storage_limits_and_eviction_criteria/index.html new file mode 100644 index 0000000000..436886fe21 --- /dev/null +++ b/files/de/web/api/indexeddb_api/browser_storage_limits_and_eviction_criteria/index.html @@ -0,0 +1,131 @@ +--- +title: Browser storage limits and eviction criteria +slug: Web/API/IndexedDB_API/Browser_storage_limits_and_eviction_criteria +tags: + - Datenbank + - Datenlöschung + - IndexDB + - Speicher + - Speicherung + - client-seitig +translation_of: Web/API/IndexedDB_API/Browser_storage_limits_and_eviction_criteria +--- +
{{DefaultAPISidebar("IndexedDB")}}
+ +

Es gibt eine Reihe von Web-Technologien, die Daten auf die eine oder andere Art und Weise client-seitig speichern (bspw. auf der lokalen Festplatte). Der Prozess, durch welchen der Browser bestimmt, wieviel Speicherplatz er der Webdatenspeicherung zur Verfügung stellen soll, und was gelöscht werden soll, wenn dieses Limit erreicht wurde, ist nicht einfach und unterscheidet sich zwischen verschiedenen Browsern. Dieser Artikel versucht zu erklären, wie dies funktioniert.

+ +
+

Info: Die untenstehenden Informationen sollten für die meisten modernen Browser zutreffen. Wo bekannt, werden browserspezifische Eigenheiten benannt. Opera und Chrome sollten sich in allen Fällen gleich verhalten. Opera Mini (noch presto-basiert, serverseitiges Rendering) speichert kein Daten lokal auf dem Client.

+
+ +

Welche Technologien nutzen Browser zur lokalen Datenspeicherung?

+ +

In Firefox werden die folgenden Technologien eingesetzt, um Daten lokal bei Bedarf zu sichern. Wir bezeichnen sie in diesem Zusammenhang als "Quota Clients" :

+ + + +
+

Info: In Firefox, Web Storage wird bald die gleichen Speichermanagement Tools wie in diesem Dokument beschrieben einsetzen.

+
+ +
+

Info: Im privaten Browsermodus werden die meisten Speichermethoden nicht unterstützt. Local storage Daten und Cookies werden zwar noch immer gespeichert, aber sie sind flüchtig — sie werden gelöscht, wenn das letzte private Browserfenster geschlossen wurde.

+
+ +

Die "letzte Zugriffszeit" der Quelle wird aufdatiert wenn irgendeine von ihnen aktiviert oder deaktiviert wird — die Löschung der Quelle löscht die Daten für alle diese "Quota Clients".

+ +

In Chrome/Opera kümmert sich die Quota Management API um das Quota Management für den AppCache, die IndexedDB, WebSQL und die File System API.

+ +

Unterschiedliche Typen der Datenspeicherung

+ +

Sogar wenn man die gleiche Speichermethode im gleichen Browser verwendet, muss man unterschiedliche Klassen der Datenspeicherung verstehen. Dieser Abschnitt behandelt die Unterschiede in verschiedenen Browsern.

+ +

Speicherung kann auf zwei Arten vorkommen:

+ + + +

Sobald persistente Daten gespeichert werden sollen, bekommt ein Benutzer in Firefox eine Popup-Warnung, um darauf hinzuweisen, dass die Daten dauerhaft gespeichert werden sollen und fragt gleichzeitig ab, ob er damit einverstanden ist. Temporäre Datenspeicherung löst nicht eine solche Warnung aus.

+ +

Datenspeicherung ist standardmäßig temporär. Entwickler können die Nutzung persistenten Speichers durch Aufruf der Methode {{domxref("StorageManager.persist()")}} aus der Storage API erreichen.

+ +

Wo werden die Daten gespeichert?

+ +

Jeder Speichertyp nutzt ein eigenes Repository. Hier ist ein konkretes Mapping auf die Verzeichnisse im Profil eines Firefox Benutzers (andere Browser können hiervon leicht abweichen):

+ + + +
+
+

Info: Nach Einführung der Storage API kann das "permanent" Verzeichnis als obsolet bestrachtet werden. Das "permanent" Verzeichnis beinhaltet nur noch persistente IndexedDB Datenbasen. Es macht keinen Unterschied, ob der box mode "best-effort" oder "persistent" ist — die Daten werden unter <profile>/storage/default abgelegt.

+
+
+ +
+

Info: In Firefox kann man sein Profilverzeichnis aufrufen, indem man about:support in die URL Adresszeile eingibt und den Ordner öffnen Knopf in der Zeile Profilordner drückt.

+
+ +
+

Info: Wenn man im Profilordner in den Datenspeicherordnern sucht, findet man noch einen vierten Ordner namens persistent. Der persistent Ordner wurde ursprünglich vor einer Weile in permanent umbenannt, um Upgrades und Migrationen zu vereinfachen.

+
+ +
+

Info: Benuter sollten unter dem Verzeichnis <profile>/storage keine eigenen dateien oder Verzeichnisse anlegen. Dies führt dazu, dass die Speicherinitialisierung fehlschlägt; zum Beispiel führt dann {{domxref("IDBFactory.open()", "open()")}} zu einem Fehlerevent.

+
+ +

Speichergrenzen

+ +

Der maximale Speicherplatz des Browsers ist dynamisch — er basiert auf der Größe der Festplatte. Das globale Limit berechnet sich als 50% des freien Plattenspeichers. In Firefox überwacht ein internes Tool namensQuota Manager wieviel Speicher jede Quelle nutzt und löscht gegebenenfalls Daten.

+ +

Wenn die Festplatte 500 GB freien Speicher aufweist, ist die maximale Größe des Speichers 250 GB. Wenn diese Größe überschritten wird, kommt ein Prozess namens origin eviction ins Spiel, welcher die kompletten Daten einzelner Quellen löscht, bis diese Größe wieder unterschritten wurde. Es werden nie Teile von Quellen gelöscht, da teilweise Daten einer Quelle zu Inkonsistenzen führen können.

+ +

Zudem gibt es eine weitere Begrenzung namens Gruppenlimit — dieses ist definiert als 20% des globalen Limits, aber hat ein Minimum von 10 MB und ein Maximum von 2 GB. Jede Quelle ist Teil einer Gruppe (Gruppe von Quellen). Es gibt eine Gruppe für jede eTLD+1 Domain. Zum Beispiel:

+ + + +

Innerhalb dieser Gruppe, mozilla.org, www.mozilla.org, und joe.blogs.mozilla.org können zusammen ein Maximum von 20% des globalen Limits nutzen. firefox.com hat als weitere Gruppe ein separates Maximum von 20%.

+ +

Beide Limits haben unterschiedliche Auswirkungen, wenn sie erreicht werden:

+ + + +
+

Info: Das Gruppenlimit kann nie mehr als das globale Limit sein. Bei extrem niedrigen Speicherstand von beispielsweisen 8MB globalen Limit, ist das Gruppenlimit ebenfalls nur 8MB.

+
+ +
+

Note: Wenn das Gruppenlimit überschritten wird oder eine ausgelöste automatische Datenlöschung nicht genug Speicher freiräumen kann, wirft der Browser einen QuotaExceededError.

+
+ +

LRU Policy

+ +

Wenn der verfügbare Speicherplatz aufgebnraucht wurde, startet das Quota Management eine Datenlöschung nach der LRU (Least Recently Used) Policy — die Daten der am längsten nicht benutzten Quellen werden zuerst gelöscht, dann die zweitältesten usw., bis der Browser wieder unter das Speicherlimit fällt.

+ +

Die letzte Zugriffszeit für jede Quelle wird im temporären Speicher vorgehalten. Sobald das globale Limit für temporären Speicher erreicht wurde,  (mehr dazu später), werden alle derzeit ungenutzten Quellen identifiziert (z.Bsp., ohne offene Tabs oder Apps, die aktuell auf den Datenspeicher zugreifen). Diese werden dann nach der letzten Zugriffszeit sortiert. Die am längsten ungenutzten Daten werden dann zuerst gelöscht, bis genug Speicher frei wird, dass die Operation ausgeführt werden kann, die zur Auslösung der Datenlöschung verantwortlich war.

+ +

Siehe auch

+ + diff --git a/files/de/web/api/indexeddb_api/grundkonzepte_hinter_indexeddb/index.html b/files/de/web/api/indexeddb_api/grundkonzepte_hinter_indexeddb/index.html new file mode 100644 index 0000000000..6ae6f33dd7 --- /dev/null +++ b/files/de/web/api/indexeddb_api/grundkonzepte_hinter_indexeddb/index.html @@ -0,0 +1,194 @@ +--- +title: Grundkonzepte +slug: Web/API/IndexedDB_API/Grundkonzepte_hinter_IndexedDB +translation_of: Web/API/IndexedDB_API/Basic_Concepts_Behind_IndexedDB +--- +

IndexedDB ermöglicht es Ihnen Daten innerhalb des Browsers eines Benutzers permanent abzulegen. Weil es Sie Webanwendungen mit funktionsreichen Abfragemöglichkeiten erstellen lässt, können diese Anwendungen sowohl online als auch offline funktionieren. IndexedDB ist geeignet für Anwendungen, die eine große Menge an Daten speichern (z.B. ein Katalog von DVDs in einer Videothek) und Anwendungen, die keine durchgehende Internetverbindung benötigen um zu funktionieren (z.B. E-Mail-Clients, To-Do-Listen oder Notizen).

+

Über dieses Dokument

+

Diese Einführung bespricht wesentliche Konzepte und Fachbegriffe in IndexedDB. Sie liefert Ihnen einen Gesamtüberblick und führt Sie in die Schlüsselkonzepte ein. Um mehr über die Begrifflichkeiten von IndexedDB zu erfahren, lesen Sie den Abschnitt Definitionen.

+

Eine Anleitung zur Verwendung der API finden Sie im Artikel Using IndexedDB. Eine Referenzdokumentierung der IndexedDB-API finden Sie im Artikel IndexedDB und dessen Unterseiten, welche die Objekttypen dokumentiert, die von IndexedDB verwendet werden, ebenso wie die Methoden von synchronen wie asynchronen APIs.

+

Überblick über IndexedDB

+

Mit IndexedDB lassen sich indizierte Objekte mit „Schlüsseln“ ablegen und abrufen. Alle Änderungen an der Datenbank geschehen innerhalb von Transaktionen. Wie die meisten Webspeicher-Lösungen folgt IndexedDB einer Same-Origin-Policy. Während also auf Daten, die innerhalb einer Domain gespeichert wurden, zugegriffen werden kann, kann nicht domainübergreifend auf Daten zugegriffen werden.

+

Die API umfasst sowohl eine asynchrone API als auch eine synchrone API. Die asynchrone API kann für die meisten Fälle verwendet werden, auch für WebWorkers, während die synchrone API nur für den Gebrauch durch WebWorkers gedacht ist. Momentan wird die synchrone API von keinem der großen Browser unterstützt. Aber selbst wenn synchrone APIs unterstützt wären, würden Sie eher die asynchrone API verwenden, wenn Sie mit IndexedDB arbeiten.

+

IndexedDB ist eine Alternative zur WebSQL-Datenbank, welche vom W3C am 18. November 2010 als veraltet erklärt wurde. Während sowohl IndexedDB als auch WebSQL Lösungen zur Speicherung von Daten bieten, bieten sie nicht dieselben Funktionalitäten. WebSQL-Datenbank ist ein relationales Datenbankanfragesystem, IndexedDB hingegen ist ein indiziertes Tabellensystem.

+

Wichtige Konzepte

+

Wenn Sie die Arbeit mit anderen Datenbanksystemen gewohnt sind kann die Arbeit mit IndexedDB am Anfang ungewohnt erscheinen. Behalten Sie deshalb folgende wichtige Konzepte im Hinterkopf:

+ +

Definitionen

+

Dieser Abschitt definiert und erklärt Begriffe, die in der IndexedDB-API verwendet werden.

+

Datenbank

+
+
+ Datenbank
+
+ Ein Aufbewahrungsort für Informationen, typischerweise bestehend aus einem oder mehreren Objektspeichern. Jede Datenbank muss folgende Angaben enthalten: +
    +
  • Name. Er identifiziert die Datenbank innerhalb einer konkreten Herkunft und verändert sich nicht innerhalb seiner Lebenszeit. Der Name kann aus einem beliebigen String-Wert bestehen (einschließlich dem leeren String).
  • +
  • +

    Aktuelle Version. Wenn eine Datenbank zum ersten Mal erstellt wird, nimmt ihre Version den integer-Wert 1 an, wenn nichts anderes angegeben wird. Jede Datenbank kann zu einem Zeitpunkt nur eine Version haben.

    +
  • +
+
+
+ Objektspeicher
+
+

Das Instrument, mit welchem Daten in einer Datenbank gespeichert werden. Der Objektspeicher hält Eintragungen aus Schlüssel-Wert-Paaren permanent. Eintragungen innerhalb eines Objektspeichers werden entsprechend der Schlüssel in aufsteigender Reihenfolge sortiert.

+

Jeder Objektspeicher muss einen Namen haben, der innerhalb seiner Datenbank einzigartig ist. Der Objektspeicher kann optional einen Schlüsselerzeuger und einen Schlüsselpfad besitzen. Wenn der Objektspeicher einen Schlüsselpfad hat, verwendet er in-line keys; ansonsten out-of-line keys.

+

Eine Referenzdokumentation zu Objektspeichern finden Sie unter IDBObjectStore oder IDBObjectStoreSync.

+
+
+ Version
+
+ Wenn eine Datenbank zum ersten Mal erstellt wird, ist ihre Versionsnummer die integer-Zahl 1. Jede Datenbank hat zu jedem Zeitpunkt genau eine Versionsnummer; eine Datenbank kann nicht in verschiedenen Versionen gleichzeitig existieren. Die Versionsnummer kann nur geändert werden, indem die Datenbank mit einer größeren Versionsnummer geöffnet wird als mit der aktuellen. Das wird die Transaktion versionchange starten und ein upgradeneeded Ereignis auslösen. Die einzige Stelle, an der das Schema der Datenbank geupdatet werden kann, ist innerhalb des Handlers dieses Ereignisses.
+  
+
+ Anmerkung: Diese Definition beschreibt die aktuellsten Spezifikationen, welche nur in Browsern auf dem neuesten Stand implementiert sind. In alten Browsern ist die mittlerweile veraltete und entfernte Methode IDBDatabase.setVersion() implementiert.
+
+ Datenbankverbindung
+
+ Eine Operation, die beim Öffnen einer Datenbank erstellt wird. Eine vorgegebene Datenbank kann mehrere Verbindungen gleichzeitig haben.
+
+ Transaktion
+
+

Eine nicht teilbare und dauerhafte Menge an Datenzugriffs- und Datenmodifikationsoperationen auf einer bestimmten Datenbank. Durch Transaktionen können Sie auf die Daten einer Datenbank zugreifen. Tatsächlich muss jeder Lese- oder Schreibvorgang von Daten in einer Transaktion stattfinden.
+
+ Eine Datenbankverbindung kann mit mehreren aktiven Transaktionen gleichzeitig verknüpft sein, so lange schreibende Transaktionen keine überlappenden scopes haben. 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.

+
+
+ Anfrage
+
+ Die Operation, mit der Lese- und Schreibvorgänge auf einer Datenbank ausgeführt werden. Jede Anfrage repräsentiert eine Lese- oder Schreiboperation.
+
+ Index
+
+

Ein Spezialobjektspeicher zum Nachschlagen von Einträgen eines anderen Objektspeichers, bezeichnet als referenzierter Objektspeicher. Der Index ist ein persistenter Schlüssel-Wert-Speicher, wobei der Wert seiner Einträge dem Schlüssel eines Eintrages im referenzierten Objektspeicher entspricht. Die Einträge in einem Index werden automatisch eingepflegt, sobald Einträge im referenzierten Objekt eingefügt, aktualisiert oder entfernt werden. Jeder Eintrag in einem Index kann auf nur einen Eintrag in seinem referenzierten Objektspeicher zeigen, aber mehrere Indizes können auf denselben Objektspeicher verweisen. Wenn der Objektspeicher sich ändert, werden alle Indizes, die auf ihn verweisen, automatisch aktualisiert.

+

Alternativ können Einträge eines Objektspeichers mithilfe eines Schlüssels nachgeschlagen werden.

+

Um mehr über die Verwendung von Indizes zu erfahren, lesen Sie Using IndexedDB. Die Referenzdokumentation zu Indizes finden Sie unter IDBKeyRange.

+
+
+

Schlüssel und Wert

+
+
+ Schlüssel
+
+

Ein Datenwert über welchen abgelegte Werte aus dem Objektspeicher sortiert und ausgelesen werden können. Der Objektspeicher kann den Schlüssel aus einer dieser drei Quellen erlangen: Einem Schlüsselgenerator, einem Schlüsselpfad und einem explizit angegebem Wert. Der Schlüssel muss aus einem Datentyp bestehen, der eine Nummer hat, die größer ist als die des Schlüssel vor ihm. Jeder Eintrag in einem Objektspeicher muss einen innerhalb des gleichen Objektspeichers einzigartigen Schlüssel haben, deshalb können nicht mehrere Einträge mit demselben Schlüssel in einem vorgegebenem Objektspeicher vorliegen.
+
+ Ein Schlüssel kann einen der folgenden Typen haben: string, date, float und array. Bei Arrays kann der Schlüssel zwischen einem leeren Wert und unendlich liegen. Arrays können wiederum Arrays beinhalten. Es gibt keine Vorschrift nur Schlüssel der Typen string oder integer zu verwenden {{ fx_minversion_inline("11") }}.

+

Alternativ können Sie Einträge eines Objektspeichers auch mithilfe eines Index nachschlagen.

+
+
+ Schlüsselgenerator
+
+ Ein Mechanismus um neue Schlüssel in einer angeordneten Reihenfolge zu erzeugen. Wenn ein Objektspeicher über keinen Schlüsselgenerator verfügt, muss die Anwendung Schlüssel für zu speichernde Einträge zur Verfügung stellen. Generatoren werden nicht zwischen Speichern geteilt. Dies ist mehr ein Detail von Browserimplementierungen, da in der Webentwicklung nicht wirklich Schlüsselgeneratoren erzeugt oder auf sie zugegriffen wird.
+
+ 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 a value 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. 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") }}.

+
+
+

Range and scope

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

+
+
+

Limitations

+

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.

+
+

Warning: At the moment due to bugs or on purpose it's impossible to open an IndexedDB database from a Web App. This needs more investigation and then be documented.

+
+

Next step

+

OK, so, now 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

+

Specification

+ +

Reference

+ +

Tutorials

+ +

Related article

+ diff --git a/files/de/web/api/indexeddb_api/index.html b/files/de/web/api/indexeddb_api/index.html new file mode 100644 index 0000000000..171ca8a4c5 --- /dev/null +++ b/files/de/web/api/indexeddb_api/index.html @@ -0,0 +1,252 @@ +--- +title: IndexedDB +slug: Web/API/IndexedDB_API +tags: + - API + - Datenbank + - Einstieg + - IndexedDB + - NeedsTranslation + - Referenz + - Speicher + - TopicStub + - speichern +translation_of: Web/API/IndexedDB_API +--- +
{{DefaultAPISidebar("IndexedDB")}}
+ +

IndexedDB ist eine low-level API für die clientseitige Speicherung großer Mengen strukturierter Daten einschließlich Dateien. Sie erlaubt auch Hochleistungssuchen dieser Daten durch die Verwendung von Indizes. Während der DOM Speicher nützlich zur Speicherung kleiner Datenmengen ist, ist er für größere Mengen strukturierte Daten wenig hilfreich. IndexedDB stellt hierfür eine Lösung bereit. Dies ist die Einstiegsseite der IndexedDB Referenz von MDN — hier stellen wir Links zur vollständigen API Referenz, Gebrauchsanleitungen, Unterstützungsdetails der Browser und einige Erklärungen des Schlüsselkonzepts zur Verfügung.

+ +

{{AvailableInWorkers}}

+ +
+

Anmerkung: Die IndexedDB API ist leistungsfähig, kann aber für einfache Anwendungen zu kompliziert erscheinen. Wenn Du eine einfachere API bevorzugst, versuche Sammlungen wie localForage und dexie.js. Diese machen IndexedDB benutzerfreundlicher.

+
+ +
+

Anmerkung: Manche älteren Browser unterstützen IndexedDB nicht aber sie unterstützen WebSQL. Eine Möglichkeit dieses Problem zu umgehen ist es, mittels polyfill auf WebSQL oder auch auf localStorage für nicht unterstützende Browser zurückzugreifen. Das beste erhältiche polyfill ist derzeit localForage.

+
+ +

Schlüsselkonzepte und Gebrauch

+ +

IndexedDB ist ein direktes Datenbank System, wie ein SQL-basiertes RDMS; während allerdings das Letztere Tabellen mit fixen Spalten benutzt, ist IndexedDB eine JavaScript-basierte objekt-orientierte Datenbank. IndexedDB läßt dich Objekte, die mit einem Schlüssel indiziert sind, speichern und wiederfinden. Jedes Objekt, das von einem strukturierten Klon Algorithmus unterstützt wird, kann gespeichert werden. Du brauchst zum Beschreiben des Datenbankschemas eine offene Verbindung zu deiner Datenbank, dann kannst du Daten mit einer Reihe von Tranaktionen wiederfinden und aktualisieren.

+ + + +
+

Anmerkung: wie die meisten Web Speicher Lösungen folgt IndexedDB einem gleicher-Ursprung Grundsatz. Deshalb ist es nicht möglich auf Daten anderer Domänen zuzugreifen, während man auf gespeicherte Daten innerhalb einer Domäne zugreift.

+
+ +

Synchron und asynchron

+ +

Operationen unter Verwendung von IndexedDB werden asynchron durchgeführt, um Anwendungen nicht zu blockieren. IndexedDB beinhaltete ursprünglich eine asynchrone und eine synchrone API; die synchrone API war nur für den Gebrauch von Web Workers gedacht. Die synchrone Version wurde aus der Spezifikation entfernt, weil ihre Notwendigkeit fraglich war, aber sie kann in Zukunft wieder eingeführt werden, wenn es genug Nachfrage von Web Entwicklern gibt.

+ +

Speichergrenzen und Löschkriterien

+ +

Es gibt mehrere Webtechnologien, um Daten auf die eine oder andere Art auf der Client Seite zu speichern (d. h. auf deiner lokalen Festplatte), über IndexedDB wird dabei am häufigsten geredet. Der Prozess mit dem der Browser herausfindet, wieviel Speicherplatz Webdaten zur Verfügung gestellt werden soll und was gelöscht werden soll, wenn die Grenze erreicht ist, ist nicht einfach und unterscheidet sich zwischen den Browsern. Browser Speichergrenzen und Löschkriterien versuchen zu erklären, wie das geschieht - zumindest im Fall von Firefox.

+ +

IndexedDB Schnittstellen

+ +

Um Zugang zu einer Datenbank zu erhalten, benutze open() von den indexedDB Attributen eines window Objekts. Diese Methode gibt ein {{domxref("IDBRequest")}} Objekt zurück; asynchrone Operationen kommunizieren mit der aufrufenden Anwendung durch feuern von Events von {{domxref("IDBRequest")}} Objekten.

+ +

Mit einer Datenbank verbinden

+ +
+
{{domxref("IDBEnvironment")}}
+
Stellt den Zugang zur IndexedDB Funktionalität zur Verfügung. Es ist implementiert durch die {{domxref("window")}} und {{domxref("worker")}} Objekte.
+
{{domxref("IDBFactory")}}
+
Stellt den Zugang zu einer Datenbank bereit. Dies ist die durch das globale Objekt indexedDB bereitgestellte Schnittstelle und dadurch der Eingangspunkt für die API.
+
{{domxref("IDBOpenDBRequest")}}
+
Stellt eine Anfrage zum Öffnen einer Datenbank dar.
+
{{domxref("IDBDatabase")}}
+
Repräsentiert eine Verbindung zu einer Datenbank. Es ist der einzige Weg eine Transaktion in der Datenbank zu erreichen.
+
+ +
+
{{domxref("IDBRequest")}}
+
Eine allgemeine Schnittstelle, die Datenbankabfragen behandelt und den Zugang zu Ergebnissen bereitstellt.
+
+ +

Abrufen und modifizieren von Daten

+ +
+
{{domxref("IDBTransaction")}}
+
Stellt eine Transaktion dar. Du erstellst eine Transaktion zu einer Datenbank, beschreibst den Geltungsbereich (beispielsweise auf welchen Objekt Speicher du zugreifen willst), und bestimmst die Art des Zugriffs (nur lesen oder lesen und schreiben), den du willst.
+
{{domxref("IDBObjectStore")}}
+
Steht für einen Objektspeicher, der Zugriff auf einen Datensatz in einer IndexedDB Datenbank erlaubt via Primärschlüsselsuche.
+
{{domxref("IDBIndex")}}
+
Gestattet ebenfalls Zugriff auf eine Teilmenge von Daten in einer IndexedDB Datenbank. Nutzt allerdings einen Index anstelle eines Primärschlüssels um an Einträge zu gelangen. Dies kann schneller sein als die Verwendung von {{domxref("IDBObjectStore")}}.
+
{{domxref("IDBCursor")}}
+
Iterates over object stores and indexes.
+
{{domxref("IDBCursorWithValue")}}
+
Iterates over object stores and indexes and returns the cursor's current value.
+
{{domxref("IDBKeyRange")}}
+
Defines a key range that can be used to retrieve data from a database in a certain range.
+
{{domxref("IDBLocaleAwareKeyRange")}} {{Non-standard_inline}}
+
Defines a key range that can be used to retrieve data from a database in a certain range, sorted acording to the rules of the locale specified for a certain index (see createIndex()'s optionalParameters.).
+
+ +

Custom event interfaces

+ +

This specification fires events with the following custom interface:

+ +
+
{{domxref("IDBVersionChangeEvent")}}
+
The IDBVersionChangeEvent interface indicates that the version of the database has changed, as the result of an {{domxref("IDBOpenDBRequest.onupgradeneeded")}} event handler function.
+
+ +

Obsolete interfaces

+ +

An early version of the specification also defined these now removed interfaces. They are still documented in case you need to update previously written code:

+ +
+
{{domxref("IDBVersionChangeRequest")}} {{obsolete_inline}}
+
Represents a request to change the version of a database. The way to change the version of the database has since changed (by calling {{domxref("IDBFactory.open")}} without also calling {{domxref("IDBDatabase.setVersion")}}), and the interface {{domxref("IDBOpenDBRequest")}} now has the functionality of the removed {{domxref("IDBVersionChangeRequest")}}.
+
{{domxref("IDBDatabaseException")}} {{obsolete_inline}}
+
Represents exception conditions that can be encountered while performing database operations.
+
{{domxref("IDBTransactionSync")}} {{obsolete_inline}}
+
Sync version of {{domxref("IDBTransaction")}}.
+
{{domxref("IDBObjectStoreSync")}} {{obsolete_inline}}
+
Sync version of {{domxref("IDBObjectStore")}}.
+
{{domxref("IDBIndexSync")}} {{obsolete_inline}}
+
Sync version of {{domxref("IDBIndex")}}.
+
{{domxref("IDBFactorySync")}} {{obsolete_inline}}
+
Sync version of {{domxref("IDBFactory")}}.
+
{{domxref("IDBEnvironmentSync")}} {{obsolete_inline}}
+
Sync version of {{domxref("IDBEnvironment")}}.
+
{{domxref("IDBDatabaseSync")}} {{obsolete_inline}}
+
Sync version of {{domxref("IDBDatabase")}}.
+
{{domxref("IDBCursorSync")}} {{obsolete_inline}}
+
Sync version of {{domxref("IDBCursor")}}.
+
+ +

Examples

+ + + +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('IndexedDB', '#idl-def-IDBEnvironment', 'IDBEnvironment')}}{{Spec2('IndexedDB')}}Initial definition
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support +

23.0 {{property_prefix("webkit")}}
+ 24

+
{{CompatGeckoDesktop("10.0")}} {{property_prefix("moz")}}
+ {{CompatGeckoDesktop("16.0")}}
10, partial157.1
Available in workers{{CompatVersionUnknown}}{{CompatGeckoDesktop("37.0")}}[1]{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}
IDBLocaleAwareKeyRange{{CompatNo}}{{CompatGeckoDesktop("43.0")}}[2]{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)Firefox OSIE PhoneOpera MobileSafari Mobile
Basic support4.4{{CompatGeckoMobile("22.0")}}1.0.110228
Available in workers{{CompatVersionUnknown}}{{CompatGeckoMobile("37.0")}}[1]{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}
IDBLocaleAwareKeyRange{{CompatNo}}{{CompatGeckoMobile("43.0")}}[2]2.5[2]{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ + + +

See also

+ + diff --git a/files/de/web/api/indexeddb_api/indexeddb_verwenden/index.html b/files/de/web/api/indexeddb_api/indexeddb_verwenden/index.html new file mode 100644 index 0000000000..3d6d61cf3f --- /dev/null +++ b/files/de/web/api/indexeddb_api/indexeddb_verwenden/index.html @@ -0,0 +1,1180 @@ +--- +title: Verwendung von IndexedDB +slug: Web/API/IndexedDB_API/IndexedDB_verwenden +translation_of: Web/API/IndexedDB_API/Using_IndexedDB +--- +

Mit IndexedDB lassen sich Daten innerhalb des Browsers eines Benutzers permanent abzulegen. Es können so Webanwendungen mit funktionsreichen Abfragemöglichkeiten in Anwendungen erstellt werden, die sowohl online als auch offline funktionieren können, da keine Netzwerkfunktionalitäten benötigt werden.

+ +

Über dieses Dokument

+ +

Dieses Tutorial bespricht die Verwendung der asynchronen API von IndexedDB. Wenn Sie nicht mit IndexedDB vertraut sind, sollten Sie zuerst den Artikel Grundkonzepte lesen.

+ +

Eine Referenzdokumentation zur IndexedDB-API finden Sie im Artikel IndexedDB und dessen Unterseiten, welche die Typen und Objekten dokumentieren, die von IndexedDB verwendet werden, ebenso wie die Methoden von sowohl synchronen als auch asynchronen APIs.

+ +

Grundschema

+ +

Das von IndexedDB unterstützte Grundschema sieht folgendermaßen aus:

+ +
    +
  1. Öffne eine Datenbank und starte eine Transaktion.
  2. +
  3. Erzeuge einen Objektspeicher.
  4. +
  5. Fordere die Ausführung von Datenbankoperationen an, wie das Hinzufügen und Auslesen von Daten.
  6. +
  7. Warte auf die richtige Art von DOM-Ereignis, das auftritt, wenn die Operation beendet ist.
  8. +
  9. Verarbeite die Ergebnisse? (, welche im Anforderungsobjekt gefunden werden können).
  10. +
+ +

Mit dem Wissen über diese Grundkonzepte können wir uns nun konkreteren Dingen zuwenden.

+ +

Erzeugung und Strukturierung des Speichers

+ +

Weil sich die Spezifizierung noch in der Entwicklung befindet, verstecken sich aktuelle Implementierungen von IndexedDB unter Browserpräfixen. Bis sich die Spezifizierung verfestigt, könne Browserhersteller unterschiedliche Implementierungen der Standard-IndexedDB-API haben. Aber sobald Konsens auf dem Standard herrscht, implementieren die Hersteller ihn ohne Markierung durch Präfixe. Tatsächlich ist in manchen Implementierungen der Präfix entfernt: Internet Explorer 10, Firefox 16, Chrome 24. Wenn auf Gecko basierende Browser einen Präfix verwenden, dann verwenden sie den Präfix moz, während auf WebKit basierende Browser den Präfix webkit verwenden.

+ +

Verwendung einer experimentellen Version von IndexedDB

+ +

Für den Fall, dass Sie Ihren Code in Browsern verwenden wollen, die noch Präfixe verwenden, können Sie folgenden Code benutzen:

+ +
// In der folgenden Zeile sollten Sie die Präfixe einfügen, die Sie testen wollen.
+window.indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;
+// Verwenden Sie "var indexedDB = ..." NICHT außerhalb einer Funktion.
+// Ferner benötigen Sie evtl. Referenzen zu einigen window.IDB* Objekten:
+window.IDBTransaction = window.IDBTransaction || window.webkitIDBTransaction || window.msIDBTransaction;
+window.IDBKeyRange = window.IDBKeyRange || window.webkitIDBKeyRange || window.msIDBKeyRange;
+// (Mozilla hat diese Objekte nie mit Präfixen versehen, also brauchen wir kein window.mozIDB*)
+ +

Beachten Sie, dass Implementierungen, die Präfixe verwenden, fehlerhaft oder unvollständig sein können oder einer alten Version der Spezifizierung folgen können. Deshalb ist es nicht empfohlen, sie im Produktivsystem zu verwenden. In manchen Fällen kann es sinnvoll sein, lieber einen Browser nicht zu unterstützen als zu behaupten, er würde unterstützt, und dann Fehler einzubüßen:

+ +
if (!window.indexedDB) {
+    window.alert("Ihr Browser unterstützt keine stabile Version von IndexedDB. Dieses und jenes Feature wird Ihnen nicht zur Verfügung stehen.");
+}
+
+ +

Öffnen einer Datenbank

+ +

Wir starten den ganzen Prozess folgendermaßen:

+ +
// Öffnen unserer Datenbank
+var request = window.indexedDB.open("MeineTestdatenbank", 3);
+
+ +

Sie sehen, das Öffnen einer Datenbank funktioniert wie jede andere Operation – Sie müssen sie „anfordern“.

+ +

Die Anforderung zum Öffnen öffnet nicht sofort die Datenbank und startet auch die Transaktion nicht gleich. Der Aufruf zur open() Funktion gibt ein IDBOpenDBRequest-Objekt mit Ergebniswert (Erfolg) oder Fehlerwert zurück, die Sie als Ereignis verarbeiten. Die meisten anderen asynchronen Funktionen in IndexedDB machen das gleiche – sie geben ein IDBRequest-Objekt mit Ergebnis oder Fehler zurück. Das Ergebnis für die open-Funktion ist eine Instanz einer IDBDatabase.

+ +

Der zweite Parameter der open-Methode ist die Version der Datenbank. Die Version der Datenbank bestimmt das Datenbankschema – den Objektspeichern und ihrer Strukturen. Wenn die angeforderte Version nicht existiert (weil die Datenbank neu ist, oder weil die Version aktualisiert wurde), wird das Ereignis onupgradeneeded ausgelöst, und es lässt sich eine neue Version der Datenbank im Handler für dieses Ereignis erzeugen. Mehr dazu später im Abschnitt Aktualisieren der Version der Datenbank.

+ +

Erzeugen von Handlern

+ +

Das erste, was Sie mit fast allen Anforderungen machen wollen, die Sie erzeugen, ist das Hinzufügen von Handlern für Erfolge und Fehler:

+ +
request.onerror = function(event) {
+  // Machen Sie etwas mit request.errorCode!
+};
+request.onsuccess = function(event) {
+  // Machen Sie etwas mit request.result!
+};
+ +

Welche der beiden Funktionen, onsuccess() oder onerror(), wird aufgerufen? Wenn alles fehlerfrei ablief, wird ein Erfolgsereignis (d.h. ein DOM-Ereignis, dessen type Eigenschaft auf "success" gesetzt ist) mit request als target ausgelöst. Sobald es ausgelöst wurde, wird die Funktion onsuccess() auf request ausgelöst mit dem Erfolgsereignis als Argument. Wenn nicht alles fehlerfrei ablief, wird ein Fehlerereignis (d.h. ein DOM-Ereignis, dessen type Eigenschaft auf "error" gesetzt ist) auf request ausgelöst. Dies löst die Funktion onerror() aus mit dem Fehlerereignis als Argument.

+ +

Die IndexedDB-API ist so entworfen, dass sie die Notwendigkeit zur Fehlerbehandlung minimiert, also werden Sie wahrscheinlich nicht viele Fehlerereignisse sehen (zumindest nicht nachdem Sie sich an die API gewöhnt haben!). Beim Öffnen von Datenbanken jedoch gibt es ein paar typische Zustände, die Fehlerereignisse erzeugen. Das wahrscheinlichste Problem ist, dass der Benutzer festgelegt hat, den Webapps das Erzeugen von Datenbanken nicht zu erlauben. Eines der Hauptentwurfsziele von IndexedDB ist es, das Speichern von großen Datenmengen zur Offline-Verwendung zu erlauben. (Um mehr darüber zu erfahren, wieviel Speicher jedem Browser zur Verfügung steht, lesen Sie Storage limits).

+ +

Offensichtlich wollen Browser nicht irgendeinem Werbenetzwerk oder einer böswilligen Website erlauben, Ihren Computer zu verschmutzen, deshalb warnen Browser den Benutzer, wenn eine Webapp zum ersten Mal versucht einen IndexedDB-Speicher zu öffnen. Der Benutzer kann wählen, ob er den Zugriff erlaubt oder verbietet. Außerdem ist IndexedDB komplett deaktiviert im Privaten Modus der Browser (Privater Modus für Firefox und Incognito Modus für Chrome). Der Hauptzweck vom Surfen im Privaten Modus ist es, keine Spuren zu hinterlassen, daher schlägt der Versuch fehl, eine Datenbank in diesem Modus zu öffnen.

+ +

Nun nehmen wir an, dass der Benutzer Ihren Anfragen erlaubt hat, eine Datenbank zu erstellen, und Sie haben ein Erfolgsereignis erhalten, um den Erfolgs-Callback auszulösen; was kommt als nächstes? Die Anfrage wurde hier mit einem Aufruf von indexedDB.open() erzeugt, also ist request.result eine Instanz von IDBDatabase, und Sie wollen diese auf jeden Fall für später speichern. Ihr Code könnte etwa so aussehen:

+ +
var db;
+var request = indexedDB.open("MeineTestdatenbank");
+request.onerror = function(event) {
+  alert("Warum haben Sie meiner Webapp nicht erlaubt IndexedDB zu verwenden?!");
+};
+request.onsuccess = function(event) {
+  db = request.result;
+};
+
+ +

Fehlerbehandlung

+ +

Wie bereits oben erwähnt, werden Error events bei entsprechenden Fehlern ausgelöst und in der Objekthierarachie weiter nach oben gereicht. Solche Fehlerereignisse  werden zunächst in der entsprechende Anfrage ausgelöst, die den Fehler verursacht hat. Anschließend werden sie zur Transaktion weitergereicht und schließlich zum Datenbankobjekt.  Wenn man nicht für jede Anfrage einen Error-Handler schreiben möchte, kann man der Datenbank einen einzigen Error-Handler hinzufügen:

+ +
db.onerror = function(event) {
+  // Allgemeine Fehlerbehandlung, die für alle Anfragen an die Datenbank gilt.
+  alert("Datenbankfehler: " + event.target.errorCode);
+};
+
+ +

Einer der häufigsten Fehler, die beim Öffnen der Datenbank auftreten, ist  VER_ERR.  Er zeigt an, dass die Versionsnummer der lokal gespeicherten Datenbank  größer  als die Versionsnummer ist,  die man zu öffnen versucht. Ein solcher Fehler muss immer durch eine Fehlerbehandlung berücksichtigt werden.

+ +

Erstellen oder Updaten der Datenbank

+ +

Wenn eine neue Version der Datenbank erstellt wird, wird das onupgradeneeded Event ausgelöst. In der Handler-Funktion dieses Events musst du für die Erstellung der Datenbankspeicher, welche für diese Version benötigt wird, sorgen:

+ +
// Dieses Event ist lediglich in modernen Browsern verfügbar
+request.onupgradeneeded = function(event) {
+  var db = event.target.result;
+
+  // Erstelle ein ObjectStore für diese Datenbank
+  var objectStore = db.createObjectStore("name", { keyPath: "myKey" });
+};
+ +

The Versionsnummer der Datenbank ist vom Typ unsigned long long, so dass sie eine sehr große Ganzzahl sein kann.

+ +
+

Das Bedeutet auch, dass sie nicht vom Typ float sein darf,  ansonsten wird sie zur nächstkleineren Ganzzahl abgerundet, so dass die Transaktion weder starten kann noch ein  upgradeneeded ausgelöst wird. Beispielsweise sollte man nicht 2.4 als Versionsnummer verwenden:

+ +
var request = indexedDB.open("MeineTestdatenbank", 2.4); // don't do this, as the version will be rounded to 2
+
+ +

Wenn man die Versionsnummer der Datenbank erhöht, wird ein  onupgradeneeded -Ereignis ausgelöst. In diesem Fall übernimmt die neue Datenbank automatisch die Objectstores von der Vorgängerversion der Datenbank, so dass man diese nicht erneut erzeugen muss. Lediglich neue Objectsores müssen angelegt oder nicht mehr gebrauchte der Vorgängerversion gelöscht werden. Wenn man einen bereits existierenden Objectstore ändern will (beispielsweise den keyPath veränden), ist es allerdings notwendig, den alten Objectstore zu löschen und einen neuen anzulegen. (Beachten Sie, dass dies die im Objectstore gespeicherten Informationen löscht, so dass man sie vorher auslesen und an anderer Stelle sichern sollte, bevor man ein Datenbankupgrade durchführt.)

+ +

WebKit unterstützt die aktuelle Version dieser Spezifikation, wie sie in Chrome 23+ ausgeliefert wird, ebenso Opera 17+ und IE10+. Andere und ältere Implementierungen unterstützen nicht die aktuelle Version dieser Spezifikation und stellen damit auch noch nicht die Möglichkeit bereit, auf die Methodensignatur indexedDB.open(name, version).onupgradeneeded zugreifen zu könenn. Um ältere Versionen einer Datenbank auf neuer Versionen zu aktualisieren, siehe IDBDatabase reference article.

+ +

Strukturierung der Datenbank

+ +

Im Folgenden wird gezeigt, wie man eine die Daten  strukturiert. IndexedDB verwendet Objectstores anstatt Tabellen, wobei eine einzelne Datenbank viele verschiedene Objectsores enthalten kann. Jeglicher Wert im Objectstore ist einem bestimmten Schlüssel (key) zugeordnet. Es werden dabei unterschiedliche Arten von Schlüsseln verarbeitet, abhängig davon, ob der Objectstore  einen key path oder einen key generator benutzt.

+ +

Die folgende Tabelle gibt eine Übersicht über die bereitgestellten Arten von Schlüssseln.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Key PathKey GeneratorBeschreibung
NeinNeinDieser Objectstore kann Daten beliebigen Typs speichern, inklusive primitiven Typen wie Zahlen und Zeichenketten (Strings). Beim Hinzufügen von Werten muss ein separater Schlüssel angegeben werden.
JaNeinDieser Objectstore kann nur JavaScript-Objekte speichern. Die Objekte müssen ein Attribut haben, dass wie der key path benannt ist.
NeinJaDieser Objectstore kann Daten beliebigen Typs speichern. Beim Hinzufügen von Werten kann ein separater Schlüssel angegeben werden. Fehlt der Schlüssel, so wird er generiert.
JaJaDieser Objectstore kann nur JavaScript-Objekte speichern. In der Regel wird der Schlüssel automatisch generiert und als gleichnamiges Attribut im Objekt gespeichert. Falls es jedoch bereits ein Attribut mit dem Namen gibt, so wird der Schlüssel nicht generiert, sondern der Wert des Attributes wird verwendet.
+ +

You can also create indices on any object store, provided the object store holds objects, not primitives. An index lets you look up the values stored in an object store using the value of a property of the stored object, rather than the object's key.

+ +

Additionally, indexes have the ability to enforce simple constraints on the stored data. By setting the unique flag when creating the index, the index ensures that no two objects are stored with both having the same value for the index's key path. So, for example, if you have an object store which holds a set of people, and you want to ensure that no two people have the same email address, you can use an index with the unique flag set to enforce this.

+ +

That may sound confusing, but this simple example should illustrate the concepts:

+ +
// This is what our customer data looks like.
+const customerData = [
+  { ssn: "444-44-4444", name: "Bill", age: 35, email: "bill@company.com" },
+  { ssn: "555-55-5555", name: "Donna", age: 32, email: "donna@home.org" }
+];
+const dbName = "the_name";
+
+var request = indexedDB.open(dbName, 2);
+
+request.onerror = function(event) {
+  // Handle errors.
+};
+request.onupgradeneeded = function(event) {
+  var db = event.target.result;
+
+  // Create an objectStore to hold information about our customers. We're
+  // going to use "ssn" as our key path because it's guaranteed to be
+  // unique.
+  var objectStore = db.createObjectStore("customers", { keyPath: "ssn" });
+
+  // Create an index to search customers by name. We may have duplicates
+  // so we can't use a unique index.
+  objectStore.createIndex("name", "name", { unique: false });
+
+  // Create an index to search customers by email. We want to ensure that
+  // no two customers have the same email, so use a unique index.
+  objectStore.createIndex("email", "email", { unique: true });
+
+  // Store values in the newly created objectStore.
+  for (var i in customerData) {
+    objectStore.add(customerData[i]);
+  }
+};
+
+ +

As mentioned previously, onupgradeneeded is the only place where you can alter the structure of the database. In it, you can create and delete object stores and build and remove indices.

+ +
Object stores are created with a single call to createObjectStore(). The method takes a name of the store, and a parameter object. Even though the parameter object is optional, it is very important, because it lets you define important optional properties and refine the type of object store you want to create. In our case, we've asked for an object store named "customers" and defined a keyPath that is the property that makes an individual object in the store unique. That property in this example is "ssn" since a social security number is guaranteed to be unique. "ssn" must be present on every object that is stored in the objectStore.
+ +

We've also asked for an index named "name" that looks at the name property of the stored objects. As with createObjectStore(), createIndex() takes an optional options object that refines the type of index that you want to create. Adding objects that don't have a name property still succeeds, but the object won't appear in the "name" index.

+ +

We can now retrieve the stored customer objects using their ssn from the object store directly, or using their name by using the index. To learn how this is done, see the section on using an index.

+ +

Hinzufügen und löschen von Daten

+ +

Before you can do anything with your new database, you need to start a transaction. Transactions come from the database object, and you have to specify which object stores you want the transaction to span. Also, you need to decide if you're going to make changes to the database or if you just need to read from it. Although transactions have three modes (read-only, read/write, and versionchange), you're better off using a read-only transaction when you can, because they can run concurrently

+ +

Daten zur Datenbank hinzufügen

+ +

If you've just created a database, then you probably want to write to it. Here's what that looks like:

+ +
var transaction = db.transaction(["customers"], "readwrite");
+// Note: Older experimental implementations use the deprecated constant IDBTransaction.READ_WRITE instead of "readwrite".
+// In case you want to support such an implementation, you can just write:
+// var transaction = db.transaction(["customers"], IDBTransaction.READ_WRITE);
+ +

The transaction() function takes two arguments (though one is optional) and returns a transaction object. The first argument is a list of object stores that the transaction will span. You can pass an empty array if you want the transaction to span all object stores, but don't do it because the spec says an empty array should generate an InvalidAccessError. If you don't specify anything for the second argument, you get a read-only transaction. Since you want to write to it here you need to pass the "readwrite" flag.

+ +

Now that you have a transaction you need to understand its lifetime. Transactions are tied very closely to the event loop. If you make a transaction and return to the event loop without using it then the transaction will become inactive. The only way to keep the transaction active is to make a request on it. When the request is finished you'll get a DOM event and, assuming that the request succeeded, you'll have another opportunity to extend the transaction during that callback. If you return to the event loop without extending the transaction then it will become inactive, and so on. As long as there are pending requests the transaction remains active. Transaction lifetimes are really very simple but it might take a little time to get used to. A few more examples will help, too. If you start seeing TRANSACTION_INACTIVE_ERR error codes then you've messed something up.

+ +

Transactions can receive DOM events of three different types: error, abort, and complete. We've talked about the way that error events bubble, so a transaction receives error events from any requests that are generated from it. A more subtle point here is that the default behavior of an error is to abort the transaction in which it occurred. Unless you handle the error by calling preventDefault() on the error event, the entire transaction is rolled back. This design forces you to think about and handle errors, but you can always add a catchall error handler to the database if fine grained error handling is too cumbersome. If you don't handle an error event or if you call abort() on the transaction, then the transaction is rolled back and an abort event is fired on the transaction. Otherwise, after all pending requests have completed, you'll get a complete event. If you're doing lots of database operations, then tracking the transaction rather than individual requests can certainly aide your sanity.

+ +

Now that you have a transaction, you'll need to get the object store from it. Transactions only let you have an object store that you specified when creating the transaction. Then you can add all the data you need.

+ +
// Do something when all the data is added to the database.
+transaction.oncomplete = function(event) {
+  alert("All done!");
+};
+
+transaction.onerror = function(event) {
+  // Don't forget to handle errors!
+};
+
+var objectStore = transaction.objectStore("customers");
+for (var i in customerData) {
+  var request = objectStore.add(customerData[i]);
+  request.onsuccess = function(event) {
+    // event.target.result == customerData[i].ssn;
+  };
+}
+ +

The result of a request generated from a call to add() is the key of the value that was added. So in this case, it should equal the ssn property of the object that was added, since the object store uses the ssn property for the key path. Note that the add() function requires that no object already be in the database with the same key. If you're trying to modify an existing entry, or you don't care if one exists already, use the put() function.

+ +

Daten aus der Datenbank löschen

+ +

Löschen von Daten ist recht ähnlich:

+ +
var request = db.transaction(["customers"], "readwrite")
+                .objectStore("customers")
+                .delete("444-44-4444");
+request.onsuccess = function(event) {
+  // It's gone!
+};
+ +

Daten aus der Datenbank auslesen

+ +

Now that the database has some info in it, you can retrieve it in several ways. First, the simple get(). You need to provide the key to retrieve the value, like so:

+ +
var transaction = db.transaction(["customers"]);
+var objectStore = transaction.objectStore("customers");
+var request = objectStore.get("444-44-4444");
+request.onerror = function(event) {
+  // Handle errors!
+};
+request.onsuccess = function(event) {
+  // Do something with the request.result!
+  alert("Name for SSN 444-44-4444 is " + request.result.name);
+};
+ +

That's a lot of code for a "simple" retrieval. Here's how you can shorten it up a bit, assuming that you handle errors at the database level:

+ +
db.transaction("customers").objectStore("customers").get("444-44-4444").onsuccess = function(event) {
+  alert("Name for SSN 444-44-4444 is " + event.target.result.name);
+};
+ +

See how this works? Since there's only one object store, you can avoid passing a list of object stores you need in your transaction and just pass the name as a string. Also, you're only reading from the database, so you don't need a "readwrite" transaction. Calling transaction() with no mode specified gives you a "readonly" transaction. Another subtlety here is that you don't actually save the request object to a variable. Since the DOM event has the request as its target you can use the event to get to the result property. Easy, right?!

+ +

Benutzung eines Cursors

+ +

Using get() requires that you know which key you want to retrieve. If you want to step through all the values in your object store, then you can use a cursor. Here's what it looks like:

+ +
var objectStore = db.transaction("customers").objectStore("customers");
+
+objectStore.openCursor().onsuccess = function(event) {
+  var cursor = event.target.result;
+  if (cursor) {
+    alert("Name for SSN " + cursor.key + " is " + cursor.value.name);
+    cursor.continue();
+  }
+  else {
+    alert("No more entries!");
+  }
+};
+ +

The openCursor() function takes several arguments. First, you can limit the range of items that are retrieved by using a key range object that we'll get to in a minute. Second, you can specify the direction that you want to iterate. In the above example, we're iterating over all objects in ascending order. The success callback for cursors is a little special. The cursor object itself is the result of the request (above we're using the shorthand, so it's event.target.result). Then the actual key and value can be found on the key and value properties of the cursor object. If you want to keep going, then you have to call continue() on the cursor. When you've reached the end of the data (or if there were no entries that matched your openCursor() request) you still get a success callback, but the result property is undefined.

+ +

One common pattern with cursors is to retrieve all objects in an object store and add them to an array, like this:

+ +
var customers = [];
+
+objectStore.openCursor().onsuccess = function(event) {
+  var cursor = event.target.result;
+  if (cursor) {
+    customers.push(cursor.value);
+    cursor.continue();
+  }
+  else {
+    alert("Got all customers: " + customers);
+  }
+};
+ +
Warnung: Die folgende Funktion ist nicht Teil des IndexedDB Standards.
+ +

Mozilla has also implemented getAll() to handle this case. It isn't part of the IndexedDB standard, so it may disappear in the future. We've included it because we think it's useful. The following code does precisely the same thing as above:

+ +
objectStore.getAll().onsuccess = function(event) {
+  alert("Got all customers: " + event.target.result);
+};
+ +

There is a performance cost associated with looking at the value property of a cursor, because the object is created lazily. When you use getAll(), Gecko must create all the objects at once. If you're just interested in looking at each of the keys, for instance, it is much more efficient to use a cursor than to use getAll(). If you're trying to get an array of all the objects in an object store, though, use getAll().

+ +

Benutzung eines Index

+ +

Storing customer data using the SSN as a key is logical since the SSN uniquely identifies an individual. (Whether this is a good idea for privacy is a different question, outside the scope of this article.) If you need to look up a customer by name, however, you'll need to iterate over every SSN in the database until you find the right one. Searching in this fashion would be very slow, so instead you can use an index.

+ +
var index = objectStore.index("name");
+index.get("Donna").onsuccess = function(event) {
+  alert("Donna's SSN is " + event.target.result.ssn);
+};
+ +

The "name" cursor isn't unique, so there could be more than one entry with the name set to "Donna". In that case you always get the one with the lowest key value.

+ +

If you need to access all the entries with a given name you can use a cursor. You can open two different types of cursors on indexes. A normal cursor maps the index property to the object in the object store. A key cursor maps the index property to the key used to store the object in the object store. The differences are illustrated here:

+ +
index.openCursor().onsuccess = function(event) {
+  var cursor = event.target.result;
+  if (cursor) {
+    // cursor.key is a name, like "Bill", and cursor.value is the whole object.
+    alert("Name: " + cursor.key + ", SSN: " + cursor.value.ssn + ", email: " + cursor.value.email);
+    cursor.continue();
+  }
+};
+
+index.openKeyCursor().onsuccess = function(event) {
+  var cursor = event.target.result;
+  if (cursor) {
+    // cursor.key is a name, like "Bill", and cursor.value is the SSN.
+    // No way to directly get the rest of the stored object.
+    alert("Name: " + cursor.key + ", SSN: " + cursor.value);
+    cursor.continue();
+  }
+};
+ +

Specifying the range and direction of cursors

+ +

If you would like to limit the range of values you see in a cursor, you can use a key range object and pass it as the first argument to openCursor() or openKeyCursor(). You can make a key range that only allows a single key, or one the has a lower or upper bound, or one that has both a lower and upper bound. The bound may be "closed" (i.e., the key range includes the given value) or "open" (i.e., the key range does not include the given value). Here's how it works:

+ +
// Only match "Donna"
+var singleKeyRange = IDBKeyRange.only("Donna");
+
+// Match anything past "Bill", including "Bill"
+var lowerBoundKeyRange = IDBKeyRange.lowerBound("Bill");
+
+// Match anything past "Bill", but don't include "Bill"
+var lowerBoundOpenKeyRange = IDBKeyRange.lowerBound("Bill", true);
+
+// Match anything up to, but not including, "Donna"
+var upperBoundOpenKeyRange = IDBKeyRange.upperBound("Donna", true);
+
+//Match anything between "Bill" and "Donna", but not including "Donna"
+var boundKeyRange = IDBKeyRange.bound("Bill", "Donna", false, true);
+
+index.openCursor(boundKeyRange).onsuccess = function(event) {
+  var cursor = event.target.result;
+  if (cursor) {
+    // Do something with the matches.
+    cursor.continue();
+  }
+};
+ +

Sometimes you may want to iterate in descending order rather than in ascending order (the default direction for all cursors). Switching direction is accomplished by passing prev to the openCursor() function:

+ +
objectStore.openCursor(null, IDBCursor.prev).onsuccess = function(event) {
+  var cursor = event.target.result;
+  if (cursor) {
+    // Do something with the entries.
+    cursor.continue();
+  }
+};
+ +

Since the "name" index isn't unique, there might be multiple entries where name is the same. Note that such a situation cannot occur with object stores since the key must always be unique. If you wish to filter out duplicates during cursor iteration over indexes, you can pass nextunique (or prevunique if you're going backwards) as the direction parameter. When nextunique or prevunique is used, the entry with the lowest key is always the one returned.

+ +
index.openKeyCursor(null, IDBCursor.nextunique).onsuccess = function(event) {
+  var cursor = event.target.result;
+  if (cursor) {
+    // Do something with the entries.
+    cursor.continue();
+  }
+};
+ +

Versionsänderung während eine Webapplikation in einem anderen Tab geöffnet ist

+ +

When your web app changes in such a way that a version change is required for your database, you need to consider what happens if the user has the old version of your app open in one tab and then loads the new version of your app in another. When you call open() with a greater version than the actual version of the database, all other open databases must explicitly acknowledge the request before you can start making changes to the database. Here's how it works:

+ +
var openReq = mozIndexedDB.open("MyTestDatabase", 2);
+
+openReq.onblocked = function(event) {
+  // If some other tab is loaded with the database, then it needs to be closed
+  // before we can proceed.
+  alert("Please close all other tabs with this site open!");
+};
+
+openReq.onupgradeneeded = function(event) {
+  // All other databases have been closed. Set everything up.
+  db.createObjectStore(/* ... */);
+  useDatabase(db);
+}
+
+openReq.onsuccess = function(event) {
+  var db = event.target.result;
+  useDatabase(db);
+  return;
+}
+
+function useDatabase(db) {
+  // Make sure to add a handler to be notified if another page requests a version
+  // change. We must close the database. This allows the other page to upgrade the database.
+  // If you don't do this then the upgrade won't happen until the user close the tab.
+  db.onversionchange = function(event) {
+    db.close();
+    alert("A new version of this page is ready. Please reload!");
+  };
+
+  // Do stuff with the database.
+}
+
+ +

Sicherheit

+ +

IndexedDB uses the same-origin principle, which means that it ties the store to the origin of the site that creates it (typically, this is the site domain or subdomain), so it cannot be accessed by any other origin.

+ +

It's important to note that IndexedDB doesn't work for content loaded into a frame from another site (either {{ HTMLElement("frame") }} or {{ HTMLElement("iframe") }}. This is a security measure. Details as to why this matters are forthcoming. See {{ bug(595307) }}.

+ +

Warnung über die Schließung des Browsers

+ +

When the browser shuts down (e.g., when the user selects Exit or clicks the Close button), any pending IndexedDB transactions are (silently) aborted -- they will not complete, and they will not trigger the error handler. Since the user can exit the browser at any time, this means that you cannot rely upon any particular transaction to complete or to know that it did not complete. There are several implications of this behavior.

+ +

First, you should take care to always leave your database in a consistent state at the end of every transaction. For example, suppose that you are using IndexedDB to store a list of items that you allow the user to edit. You save the list after the edit by clearing the object store and then writing out the new list. If you clear the object store in one transaction and write the new list in another transaction, there is a danger that the browser will close after the clear but before the write, leaving you with an empty database. To avoid this, you should combine the clear and the write into a single transaction.

+ +

Second, you should never tie database transactions to unload events. If the unload event is triggered by the browser closing, any transactions created in the unload event handler will never complete. An intuitive approach to maintaining some information across browser sessions is to read it from the database when the browser (or a particular page) is opened, update it as the user interacts with the browser, and then save it to the database when the browser (or page) closes. However, this will not work. The database transactions will be created in the unload event handler, but because they are asynchronous they will be aborted before they can execute.

+ +

In fact, there is no way to guarantee that IndexedDB transactions will complete, even with normal browser shutdown. See {{ bug(870645) }}.

+ +

Vollständiges IndexedDB Beispiel

+ +

HTML Content

+ +
<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 to uselessly reload 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();
+    // Reseting 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 than 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") }}

+ +

Nächster Schritt

+ +

If you want to start tinkering with the API, jump in to the reference documentation and checking out the different methods.

+ +

Siehe auch

+ +

Reference

+ + + +

Tutorials

+ + + +

Related articles

+ + + +

Firefox

+ + diff --git a/files/de/web/api/keyboardevent/altkey/index.html b/files/de/web/api/keyboardevent/altkey/index.html new file mode 100644 index 0000000000..3f16f6d710 --- /dev/null +++ b/files/de/web/api/keyboardevent/altkey/index.html @@ -0,0 +1,118 @@ +--- +title: KeyboardEvent.altKey +slug: Web/API/KeyboardEvent/altKey +translation_of: Web/API/KeyboardEvent/altKey +--- +

{{APIRef("DOM Events")}}

+ +

Der Konstruktor KeyboardEvent.altKey hat die Eigenschaft {{jsxref("Boolean")}} und zeigt an ob alt Taste (Option oder in OS X) gedrückt wurde (true) oder (false) nicht gerdrückt wurde, wenn das Ereignis eintritt.

+ +

Syntax

+ +
var altKeyPressed = instanceOfKeyboardEvent.altKey
+
+ +

Examples

+ +
<html>
+<head>
+<title>altKey example</title>
+
+<script type="text/javascript">
+
+function showChar(e){
+  alert(
+    "Key Pressed: " + String.fromCharCode(e.charCode) + "\n"
+    + "charCode: " + e.charCode + "\n"
+    + "ALT key pressed: " + e.altKey + "\n"
+  );
+}
+
+</script>
+</head>
+
+<body onkeypress="showChar(event);">
+<p>
+Press any character key,
+with or without holding down the ALT key.<br />
+You can also use the SHIFT key together with the ALT key.
+</p>
+</body>
+</html>
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM3 Events','#widl-KeyboardEvent-altKey','KeyboardEvent.altkey')}}{{Spec2('DOM3 Events')}}Initial definition.
+ +

Browser compatibility

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureEdgeFirefox (Gecko)ChromeInternet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown()}}{{CompatVersionUnknown()}}{{CompatVersionUnknown()}}{{CompatVersionUnknown()}}{{CompatVersionUnknown()}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureEdgeFirefox Mobile (Gecko)AndroidIE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +

See also

+ + diff --git a/files/de/web/api/keyboardevent/getmodifierstate/index.html b/files/de/web/api/keyboardevent/getmodifierstate/index.html new file mode 100644 index 0000000000..75b1c5e36d --- /dev/null +++ b/files/de/web/api/keyboardevent/getmodifierstate/index.html @@ -0,0 +1,247 @@ +--- +title: KeyboardEvent.getModifierState() +slug: Web/API/KeyboardEvent/getModifierState +translation_of: Web/API/KeyboardEvent/getModifierState +--- +

{{APIRef("DOM Events")}}

+ +

Die Methode KeyboardEvent.getModifierState() gibt den aktuellen Zustand des angegebenen Modifikators zurück: true, wenn der Modifikator aktiv ist (d.h. die Modifikationstasten gedrückt oder gesperrt ist), ansonsten false.

+ +

Syntax

+ +
var active = event.getModifierState(keyArg);
+ +

Rückgabe 

+ +

Einen {{jsxref("Boolean")}}

+ +

Parameter

+ +
+
keyArg
+
Ein Modifikatorschlüsselwert. Der Wert muss einer der {{domxref("KeyboardEvent.key")}} Werte sein, die Modifikatorschlüssel darstellen, oder die Zeichenkette "Accel" {{deprecated_inline}}. Dabei wird zwischen Groß- und Kleinschreibung unterschieden.
+
+ +

Modifikationstasten im Internet Explorer

+ +

IE9 verwendet "Scroll" für "ScrollLock" und "Win" für "OS".

+ +

Modifikationstasten in Gecko

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Wann gibt getModifierState() bei Gecko true zurück?
 WindowsLinux (GTK)MacAndroid 2.3Android 3.0 und später
"Alt"Entweder die Alt oder AltGr -Taste gedrückt wirdAlt -Taste gedrückt wird⌥ Option -Taste gedrückt wirdAlt  oder  option -Taste gedrückt wird
"AltGraph" +

Sowohl die Alt als auch die Strg  werden gedrückt, oder die AltGr Taste wird gedrückt

+
Level 3 Shift Taste (or Level 5 Shift Taste {{gecko_minversion_inline("20.0")}}) wird gedrückt⌥ Option Taste wird gedrücktNicht unterstützt
"CapsLock"Während die LED für ⇪ Caps Lock leuchtetNicht unterstütztSolange ⇪ Caps Lock gesperrt ist {{gecko_minversion_inline("29.0")}}
"Control"Entweder die Strg  oder AltGr -Taste wird gedrücktStrg Taste wird gedrücktcontrol Taste wird gedrücktmenu Taste wird gedrückt.Strg, control  oder menu Taste wird gedrückt.
"Fn"Nicht unterstütztDie Function wird gedrückt, aber wir sind nicht sicher, welche Taste den Modifikatorstatus aktiv setzt. Die Fn-Taste auf der Mac-Tastatur bewirkt dies nicht.
+ {{gecko_minversion_inline("29.0")}}
"FnLock"Nicht unterstützt
"Hyper"Nicht unterstützt
"Meta"Nicht unterstütztMeta Taste wird gedrückt {{gecko_minversion_inline("17.0")}}⌘ Command Taste wird gedrücktNicht unterstützt⊞ Windows Logo  or command Taste gedrückt wird
"NumLock"Während die LED für Num Lock leuchtetEine Taste auf dem Nummerblock gedrückt wirdNicht unterstütztSolange NumLock gesperrt ist {{gecko_minversion_inline("29.0")}}
"OS"⊞ Windows Logo Taste wird gedrücktSuper or Hyper Taste wird gedrückt (normalerweise auf der ⊞ Windows Logo Taste zugeordnet)Nicht unterstützt
"ScrollLock"Während die LED für ScrollLock leuchtetWährend die LED für ScrollLock leuchtet, aber normalerweise wird dies von der Plattform nicht unterstützt Nicht unterstütztSolange ScrollLock gesperrt {{gecko_minversion_inline("29.0")}}
"Shift"⇧ Shift Taste wird gedrückt
"Super"Nicht unterstützt
"Symbol"Nicht unterstützt
"SymbolLock"Nicht unterstützt
+ + + +

"Accel" virtueller Modifikator

+ +
Notiz: Der virtuelle Modifikator "Accel" ist in den aktuellen Entwürfen der DOM3 Events-Spezifikation praktisch veraltet.
+ +

getModifierState() also accepts a deprecated virtual modifier named "Accel". event.getModifierState("Accel") returns true when at least one of {{domxref("KeyboardEvent.ctrlKey")}} or {{domxref("KeyboardEvent.metaKey")}} is true.

+ +

In old implementations and outdated specifications, it returned true when a modifier which is the typical modifier key for the shortcut key is pressed. For example, on Windows, pressing Ctrl key may make it return true. However, on Mac, pressing ⌘ Command key may make it return true. Note that which modifier key makes it return true depends on platforms, browsers, and user settings. For example, Firefox users can customize this with a pref, "ui.key.accelKey".

+ +

Beispiel

+ +
// Ignorieren, wenn folgender Modifikator aktiv ist.
+if (event.getModifierState("Fn") ||
+    event.getModifierState("Hyper") ||
+    event.getModifierState("OS") ||
+    event.getModifierState("Super") ||
+    event.getModifierState("Win") /* hack for IE */) {
+  return;
+}
+
+// auch ignorieren, wenn zwei oder mehr Modifikatoren außer Shift aktiv sind.
+if (event.getModifierState("Control") +
+    event.getModifierState("Alt") +
+    event.getModifierState("Meta") > 1) {
+  return;
+}
+
+// Tastaturkürzel mit Standardmodifikator
+if (event.getModifierState("Accel")) {
+  switch (event.key.toLowerCase()) {
+    case "c":
+      if (event.getModifierState("Shift")) {
+        // Handle Accel + Shift + C
+        event.preventDefault(); // consume the key event
+      }
+      break;
+    case "k":
+      if (!event.getModifierState("Shift")) {
+        // Handle Accel + K
+        event.preventDefault(); // consume the key event
+      }
+      break;
+  }
+  return;
+}
+
+// Mach etwas anderes für die Pfeiltasten, wenn ScrollLock gesperrt ist.
+if ((event.getModifierState("ScrollLock") ||
+       event.getModifierState("Scroll") /* hack for IE */) &&
+    !event.getModifierState("Control") &&
+    !event.getModifierState("Alt") &&
+    !event.getModifierState("Meta")) {
+  switch (event.key) {
+    case "ArrowDown":
+    case "Down": // Hack für IE und älteren Gecko
+      event.preventDefault(); // Schlüsselereignis verwenden
+      break;
+    case "ArrowLeft":
+    case "Left": // Hack für IE und älteren Gecko
+      // Mach etwas anderes für die Pfeiltasten, wenn ScrollLock gesperrt ist.
+      event.preventDefault(); // Schlüsselereignis verwenden
+      break;
+    case "ArrowRight":
+    case "Right": // Hack für IE und älteren Gecko
+      // Mach etwas anderes für die Pfeiltasten, wenn ScrollLock gesperrt ist.
+      event.preventDefault(); // Schlüsselereignis verwenden
+      break;
+    case "ArrowUp":
+    case "Up": // Hack für IE und älteren Gecko
+      // Mach etwas anderes für die Pfeiltasten, wenn ScrollLock gesperrt ist.
+      event.preventDefault(); // Schlüsselereignis verwenden
+      break;
+  }
+}
+
+ +
+

Obwohl dieses Beispiel .getModifierState() mit "Alt", "Control", "Meta" und "Shift" verwendet, ist es vielleicht besser, altKey, ctrlKey, metaKey und shiftKey zu verwenden, da sie kürzer und vielleicht schneller sind.

+
+ +

Spezifikationen

+ + + + + + + + + + + + + + +
SpezifikationStatusKommentar
{{SpecName('DOM3 Events', '#widl-KeyboardEvent-getModifierState', 'getModifierState()')}}{{Spec2('DOM3 Events')}}Initiale Definition (Modifier Keys spec)
+ +

Browser-Kompatibilität

+ + + +

{{Compat("api.KeyboardEvent.getModifierState")}}

+ +

Siehe auch

+ + diff --git a/files/de/web/api/keyboardevent/index.html b/files/de/web/api/keyboardevent/index.html new file mode 100644 index 0000000000..6f76b0b13f --- /dev/null +++ b/files/de/web/api/keyboardevent/index.html @@ -0,0 +1,458 @@ +--- +title: KeyboardEvent +slug: Web/API/KeyboardEvent +translation_of: Web/API/KeyboardEvent +--- +
{{APIRef("DOM Events")}}
+ +

KeyboardEvent Objekte beschreiben eine Benutzerinteraktion mit dem Keyboard. Jedes Event beschreibt eine Taste. Der Eventtyp (keydown, keypress, oder keyup) identifiziert welche Art von Aktivität ausgeführt wurde.

+ +
Anmerkung: Das KeyboardEvent deutet nur an was mit einer Taste passiert. Wenn Sie Texteingaben behandeln müssen, verwenden sie stattdessen das HTML5 input Event. Beispiel: Wenn ein Benutzer Text über ein Handschriftsystem - wie auf einem Tablet - eingibt, werden Tastenevents möglicherweise nicht ausgelöst.
+ +

Konstruktor

+ +
+
{{domxref("KeyboardEvent.KeyboardEvent", "KeyboardEvent()")}}
+
Erzeugt ein KeyboardEvent Objekt.
+
+ +

Methoden

+ +

Diese Schnittstelle erbt auch Methoden seiner Eltern {{domxref("UIEvent")}} und {{domxref("Event")}}.

+ +
+
{{domxref("KeyboardEvent.getModifierState()")}}
+
Liefert einen {{jsxref("Boolean")}} Wert welcher angibt ob eine Hilfstaste wie AltShiftCtrl, oder Meta gedrückt war als das Event erzeugt wurde.
+
{{domxref("KeyboardEvent.initKeyEvent()")}}{{deprecated_inline}}
+
Initialisiert ein KeyboardEvent Objekt. Dies wurde nur durch Gecko implementiert (andere verwendeten {{domxref("KeyboardEvent.initKeyboardEvent()")}}) und sollte nicht mehr benutzt werden. Der moderne Standardweg ist, den {{domxref("KeyboardEvent.KeyboardEvent", "KeyboardEvent()")}} Konstrutor zu verwenden.
+
{{domxref("KeyboardEvent.initKeyboardEvent()")}}{{deprecated_inline}}
+
Initialisiert ein KeyboardEvent Objekt. Dies wurde nie von Gecko implementiert (da stattdessen {{domxref("KeyboardEvent.initKeyEvent()")}} verwendet wurde) und sollte nicht mehr benutzt werden. Der moderne Standardweg ist, den {{domxref("KeyboardEvent.KeyboardEvent", "KeyboardEvent()")}} Konstruktor zu verwenden.
+
+ +

Eigenschaften

+ +

Diese Schnittstelle erbt auch Methoden seiner Eltern {{domxref("UIEvent")}} und {{domxref("Event")}}.

+ +
+
{{domxref("KeyboardEvent.altKey")}} {{Readonlyinline}}
+
Liefert einen {{jsxref("Boolean")}} Wert der true ist falls die Alt ( Option oder unter OS X) Taste aktiv war, als das Tastenevent erzeugt wurde.
+
{{domxref("KeyboardEvent.char")}} {{Non-standard_inline}}{{Deprecated_inline}}{{Readonlyinline}}
+
Liefert einen {{domxref("DOMString")}} der das Zeichen der Taste repräsentiert. Wenn die Taste einem druckbaren Zeichen entspricht, ist dieser Wert eine nicht-leere Unicode-Zeichenkette die dieses Zeichen enthält. Fall die Taste keine druckbare Darstellung besitzt, ist der Wert eine leere Zeichenkette. +
Anmerkung: Falls die Taste als Makro verwendet wird, das mehrere Zeichen einfügt, ist der Wert dieses Attributs die gesamte Zeichenkette, nicht nur das erste Zeichen.
+ +
Warnung: Dies wurde aus den DOM Level 3 Events entfernt. Es wird nur von IE9+ und Microsoft Edge unterstützt.
+
+
{{domxref("KeyboardEvent.charCode")}} {{Deprecated_inline}}{{Readonlyinline}}
+
Liefert einen {{jsxref("Number")}} Wert der die Unicode-Kennziffer der Taste repräsentiert; dieses Attribut wird nur vom keypress Event verwendet. Für Tasten deren char Attribut mehrere Zeichen enthält ist der Wert dieses Attributs der Unicode-Wert des ersten Zeichens . In Firefox 26 liefert dies Codes für druckbare Zeichen. +
Warnung: Dieses Attribut ist veraltet; Sie sollten stattdessen - wenn vorhanden - {{domxref("KeyboardEvent.key")}} verwenden.
+
+
{{domxref("KeyboardEvent.code")}} {{Readonlyinline}}
+
Liefert einen {{domxref("DOMString")}} mit dem Codewert der Taste, welche durch das Event repräsentiert wird.
+
{{domxref("KeyboardEvent.ctrlKey")}} {{Readonlyinline}}
+
Liefert einen {{jsxref("Boolean")}} Wert der true ist, falls die Ctrl Taste aktiv war als  das Key-Event erzeugt wurde.
+
{{domxref("KeyboardEvent.isComposing")}} {{Readonlyinline}}
+
Liefert einen {{jsxref("Boolean")}} Wert der true ist falls das Event nach compositionstart und vor compositionend ausgelöst wird.
+
{{domxref("KeyboardEvent.key")}} {{Readonlyinline}}
+
Liefert einen {{domxref("DOMString")}} der den Wert der Taste darstellt die durch das Event repräsentiert wird.
+
{{domxref("KeyboardEvent.keyCode")}} {{deprecated_inline}}{{Readonlyinline}}
+
Liefert einen {{jsxref("Number")}} Wert der einen system- und implementationsabhängigen Zahlencode darstellt, der den unmodifizierten Wert der gedrückten Taste repräsentiert. +
Warnung: Dieses Attribut ist veraltet; Sie sollten stattdessen - wenn vorhanden - {{domxref("KeyboardEvent.key")}} verwenden.
+
+
{{domxref("KeyboardEvent.keyIdentifier")}} {{Non-standard_inline}}{{deprecated_inline}}{{Readonlyinline}}
+
Diese Eigenschaft ist nicht standardisiert und veraltet. Es sollte stattdessen {{domxref("KeyboardEvent.key")}} verwendet werden. Sie war Teil einer alten Version von DOM Level 3 Events.
+
{{domxref("KeyboardEvent.keyLocation")}} {{Non-standard_inline}}{{deprecated_inline}}{{Readonlyinline}}
+
Dies ist ein nicht-standardisierter Alias für {{domxref("KeyboardEvent.location")}}. Sie war Teil einer alten Version von DOM Level 3 Events.
+
{{domxref("KeyboardEvent.locale")}} {{Readonlyinline}}
+
Liefert einen {{domxref("DOMString")}} der das Gebietsschema identifiziert für die das Keyboard konfiguriert ist. Diese Zeichenkette kann leer sein, wenn der Browser oder das Gerät das Gebietsschema des Keyboards nicht kennt. +
Anmerkung: Dies beschreibt nicht das Gebietsschema der eingegebenen Daten. Ein Benutzer könnte ein Tastaturlayout nutzen während er Text in einer anderen Sprache eingibt.
+
+
{{domxref("KeyboardEvent.location")}} {{Readonlyinline}}
+
Liefert einen {{jsxref("Number")}} Wert der die Lage der Taste auf der Tastatur oder einem anderen Eingabegerät repräsentiert.
+
{{domxref("KeyboardEvent.metaKey")}} {{Readonlyinline}}
+
Liefert einen {{jsxref("Boolean")}} Wert der true ist, falls die Meta Taste (auf Mac-Tastaturen, die ⌘ Command Taste; auf Windows-Tastaturen, die Windows -Taste ()) aktiv war, als das Key-Event erzeugt wurde.
+
{{domxref("KeyboardEvent.repeat")}} {{Readonlyinline}}
+
Liefert einen {{jsxref("Boolean")}} Wert der true ist, falls die Taste gedrückt gehalten wird, so dass sie sich automatisch wiederholt.
+
{{domxref("KeyboardEvent.shiftKey")}} {{Readonlyinline}}
+
Liefert einen {{jsxref("Boolean")}} Wert der true ist, falls die Shift Taste aktiv war, als das Key-Event erzeugt wurde.
+
{{domxref("KeyboardEvent.which")}} {{deprecated_inline}}{{Readonlyinline}}
+
Liefert einen {{jsxref("Number")}} Wert der einen system- und implementationsabhängigen Zahlencode darstellt, der den unmodifizierten Wert der gedrückten Taste repräsentiert; das ist gewöhnlich das Gleiche wie keyCode. +
Warnung: Dieses Attribut ist veraltet; Sie sollten stattdessen - wenn vorhanden - {{domxref("KeyboardEvent.key")}} verwenden.
+
+
+ +

Anmerkungen

+ +

Es gibt keydown, keypress, and keyup Events. Für die meisten Tasten versendet Gecko eine Sequenz von Key-Events wie folgt:

+ +
    +
  1. Wenn die Taste gedrückt wird, wird ein keydown Event gesendet.
  2. +
  3. Falls die Taste keine Hilfstaste ist, wird das keypress Event gesendet.
  4. +
  5. Wenn der Nutzer die Taste loslässt, wird das keyup Event gesendet.
  6. +
+ +

Sonderfälle

+ +

Einige Taste schalten den Status einer Kontrollleuchte um; dazu gehören Caps Lock, Num Lock, und Scroll Lock. Unter Windows und Linux senden diese Tasten nur keydown and keyup Events.

+ +
+

Unter Linux versendet Firefox 12 und eher das keypress Event auch für diese Tasten.

+
+ +

Jedoch sorgen die Einschränkungen des Mac OS X Event-Modells dafür, dass  Caps Lock nur das keydown Event versendet. Num Lock wurde auf einigen älteren Laptop-Modellen (Modelle 2007 und älter) unterstützt, aber seitdem hat Mac OS X  Num Lock nicht mehr untertstützt - nicht einmal auf externen Tastaturen. Auf älteren MacBooks mit einer Num Lock Taste, erzeugt diese Taste überhaupt keine KeyEvents. Gecko unterstützt die Scroll Lock Taste, falls eine externe Tastatur, die eine F14 Taste besitzt, angeschlossen ist. In bestimmten älteren Firefox-Versionen erzeugt diese Taste ein keypress Event; dieses inkonsistente Verhalten war {{bug(602812)}}.

+ +

Behandlung von Auto-repeat

+ +

Wenn eine Taste gedrückt und gehalten wird, beginnt sie die automatische Wiederholung (sog. auto-repeat). Das Resultat ist das Versenden einer Reihe von Events ähnlich der folgenden:

+ +
    +
  1. keydown
  2. +
  3. keypress
  4. +
  5. keydown
  6. +
  7. keypress
  8. +
  9. <<wiederholt sich bis der Nutzer die Taste loslässt>>
  10. +
  11. keyup
  12. +
+ +

Das sollte laut DOM Level 3 Spezifikation passieren. Allerdings gibt es einige Ausnahmen, wie unten beschrieben.

+ +

Auto-repeat in einigen GTK-Umgebungen wie Ubuntu 9.4

+ +

In einigen GTK-basierten Umgebungen versendet auto-repeat automatisch ein natives Key-Up Event während der automatischen Wiederholung und es ist für Gecko deshalb nicht möglich zwischen wiederholten Tastendrücken und einem auto-repeat unterscheiden zu können. Auf diesen Platformen wird eine Auto-Repeat Taste also die folgende Reihe von Events erzeugen:

+ +
    +
  1. keydown
  2. +
  3. keypress
  4. +
  5. keyup
  6. +
  7. keydown
  8. +
  9. keypress
  10. +
  11. keyup
  12. +
  13. <<wiederholt sich bis der Nutzer die Taste loslässt>>
  14. +
  15. keyup
  16. +
+ +

Innerhalb dieser Umgebungen gibt es leider keine Möglichkeit für Webinhalte den Unterschied zwischen selbst-wiederholenden Tasten und Tasten die wiederholt gedrückt werden herauszufinden.

+ +

Behandlung von auto-repeat vor Gecko 5.0

+ +

Vor Gecko 5.0 {{geckoRelease('5.0')}} war platformübergreifendes Tastatur-Handling weniger einheitlich.

+ +
+
Windows
+
Das Auto-Repeat-Verhalten ist das Gleiche wie in Gecko 4.0 und später.
+
Mac
+
Nach dem initialen keydown Event werden nur keypress Events gesendet bis das keyup Event auftritt; die dazwischendliegenden keydown Events werden nicht gesendet.
+
Linux
+
Das Event-Verhalten hängt von der spezifischen Platform ab. Es wird sich entweder so verhalten wie Windows oder Mac, abhängig davon was das native Event-Modell macht.
+
+ +

Anmerkung: manuelles Auslösen eines Events erzeugt nicht die mit dem Event verbundene Standard-Aktion. Zum Beispiel: manuelles Auslösen eines KeyEvent führt nicht dazu, dass der Buchstabe in einem fokussierten Eingabefeld auftaucht. Im Fall von UI-Events ist dies aus Sicherheitsgründen wichtig, da es verhindert, dass Skripte Benutzeraktionen simulieren, die mit dem Browser selbst interagieren.

+ +

Beispiel

+ +
<!DOCTYPE html>
+<html>
+<head>
+<script>
+'use strict';
+
+document.addEventListener('keydown', (event) => {
+  const keyName = event.key;
+
+  if (keyName === 'Control') {
+    // not alert when only Control key is pressed.
+    return;
+  }
+
+  if (event.ctrlKey) {
+    // Even though event.key is not 'Control' (i.e. 'a' is pressed),
+    // event.ctrlKey may be true if Ctrl key is pressed at the time.
+    alert(`Combination of ctrlKey + ${keyName}`);
+  } else {
+    alert(`Key pressed ${keyName}`);
+  }
+}, false);
+
+document.addEventListener('keyup', (event) => {
+  const keyName = event.key;
+
+  // As the user release the Ctrl key, the key is no longer active.
+  // So event.ctrlKey is false.
+  if (keyName === 'Control') {
+    alert('Control key was released');
+  }
+}, false);
+
+</script>
+</head>
+
+<body>
+</body>
+</html>
+
+ +

Spezifikationen

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM3 Events', '#interface-keyboardevent', 'KeyboardEvent')}}{{Spec2('DOM3 Events')}}Initiale Definition
+ +

Die KeyboardEvent Schnittstelle lief durch eine Vielzahl von Entwurfsversionen, erst unter DOM Events Level 2, wo sie verworfen wurde als kein Konsens entstand, danach unter DOM Events Level 3. Dies führte zu einer Implementation von nicht standardisierten Initialisationsmethoden, der frühen DOM Events Level 2 Version {{domxref("KeyboardEvent.initKeyEvent()")}} durch Gecko Browser und die frühe DOM Events Level 3 Version, {{domxref("KeyboardEvent.initKeyboardEvent()")}} durch Andere. Beide wurden durch den modernen Einsatz eines Konstruktors ersetzt: {{domxref("KeyboardEvent.KeyboardEvent", "KeyboardEvent()")}}.

+ +

Browserkompatibilität

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
constructor{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatGeckoDesktop("31.0")}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatUnknown}}
.char{{CompatNo}}{{CompatUnknown}}{{CompatNo}}9{{CompatNo}}{{CompatNo}}
.charCode{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
.isComposing{{CompatNo}}{{CompatUnknown}}{{CompatGeckoDesktop("31.0")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
.keyCode{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
.locale{{CompatNo}}{{CompatUnknown}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}
.location{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatGeckoDesktop("15.0")}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}
.repeat{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatGeckoDesktop("28.0")}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}
.which{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
.initKeyboardEvent(){{CompatVersionUnknown}}[1]{{CompatUnknown}}{{CompatNo}}[2]{{CompatIE("9.0")}}[3]{{CompatUnknown}}{{CompatVersionUnknown}}[1]
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
constructor{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile("31.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
.char{{CompatUnknown}}{{CompatUnknown}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
.charCode{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
.isComposing{{CompatNo}}{{CompatUnknown}}{{CompatGeckoMobile("31.0")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
.keyCode{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
.locale{{CompatUnknown}}{{CompatUnknown}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
.location{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile("15.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
.repeat{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile("28.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
.which{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
.initKeyboardEvent(){{CompatUnknown}}{{CompatUnknown}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1] Die Argumente von initKeyboardEvent() von WebKit and Blink weichen von der Definition in DOM Level 3 Events ab. Die Methode ist: initKeyboardEvent(in DOMString typeArg, in boolean canBubbleArg, in boolean cancelableArg, in views::AbstractView viewArg, in DOMString keyIdentifierArg, in number locationArg, in boolean ctrlKeyArg, in boolean altKeyArg, in boolean shiftKeyArg, in boolean metaKeyArg, in boolean altGraphKeyArg)

+ +

[2] Gecko wird initKeyboardEvent() nicht unterstützen, weil es die Feature-Erkennung von Web-Apllikationen komplett zerstört. Siehe {{Bug(999645)}}.

+ +

[3] Das Argument von initKeyboardEvent() von IE weicht von der Definition in DOM Level 3 Events ab. Die Methode ist: 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). Siehe document of initKeyboardEvent() in MSDN.

+ +

Siehe auch

+ + diff --git a/files/de/web/api/keyboardevent/keycode/index.html b/files/de/web/api/keyboardevent/keycode/index.html new file mode 100644 index 0000000000..98375fe4b9 --- /dev/null +++ b/files/de/web/api/keyboardevent/keycode/index.html @@ -0,0 +1,3185 @@ +--- +title: KeyboardEvent.keyCode +slug: Web/API/KeyboardEvent/keyCode +translation_of: Web/API/KeyboardEvent/keyCode +--- +

{{APIRef("DOM Events")}}{{deprecated_header()}}

+ +

Die schreibgeschütze Eigenschaft KeyboardEvent.keyCode  stellt den den unveränderten,  System- und Implementationsabhängigen numerischen Bezeichner der gedrückten Taste dar. Normalerweise ist das der zugehörige  ASCII {{RFC(20)}}) oder Windows 1252 Code der Taste. Bei einer unerkannten Taste ist das der Wert 0.

+ +

Der Wert des keypress Ereignis unterscheided sich von Browser zu Browser. IE und Google Chrome setzen den {{domxref("KeyboardEvent.charCode")}}  Wert. Gecko setzt 0 wenn die gedrückte Taste ein druckbares Zeichen darstellt, andernfalls ist es der selbe Wert wie beim keydown und keyup Ereignis.

+ +

Von der Verwendung dieser Eigenschaft sollte nach Möglichkeit abgesehen werden, da siebereits seit einiger Zeit veraltet ist. Statdessen sollte {domxref("KeyboardEvent.code")}} verwendet werden, so es implementiert ist. Leider gibt es noch immer einige Browser ohne Unterstützung dafür. Google und Safari implementieren {{domxref("KeyboardEvent.keyIdentifier")}}, der bisher in der Entwurfs-Spezifikation enthalten ist,  nicht jedoch in der finalen Version.

+ +
+

Entwickler sollten von der Verwendung von keyCode Eigenschaft  für druckbare Zeichen bei keydown und keyup Ereignissen absehen. Wie zuvor beschrieben , ist die keyCode Eigenschaft für druckbare Zeichen nicht zu gebrauchen, vor allem wenn Shift oder Alt dabei gedrückt sind. Bei der Implementation von Kürzeln, ist das {{event("keypress")}} Ereignis meist eher angebracht (zumindest bei der Verwendung der Gecko Engine). Näheres siehe Gecko Keypress Event .

+
+ +

Beispiel

+ +
window.addEventListener("keydown", function (event) {
+  if (event.defaultPrevented) {
+    return; // Should do nothing if the default action has been cancelled
+  }
+
+  var handled = false;
+  if (event.key !== undefined) {
+    // Handle the event with KeyboardEvent.key and set handled true.
+  } else if (event.keyIdentifier !== undefined) {
+    // Handle the event with KeyboardEvent.keyIdentifier and set handled true.
+  } else if (event.keyCode !== undefined) {
+    // Handle the event with KeyboardEvent.keyCode and set handled true.
+  }
+
+  if (handled) {
+    // Suppress "double action" if event handled
+    event.preventDefault();
+  }
+}, true);
+
+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM3 Events','#widl-KeyboardEvent-keyCode','KeyboardEvent.keyCode')}}{{Spec2('DOM3 Events')}}Initiale Definition; als veraltet gekennzeichnet
+ +

Browser Kompatibilität

+ + + +

{{Compat("api.KeyboardEvent.keyCode")}}

+ +

Werte von keyCode

+ +

druckbare Tasten in der Standard-Position

+ +

The value of key events which are caused by pressing or releasing printable keys in standard position is not compatible between browsers.

+ +

IE just exposes the native virtual keycode value as KeyboardEvent.keyCode.

+ +

Google Chrome, Chromium and Safari must decide the value from the input character. If the inputting character can be inputted with the US keyboard layout, they use the keyCode value on the US keyboard layout.

+ +

Starting in Firefox 15 {{geckoRelease("15.0")}}, Gecko gets keyCode values from ASCII characters inputtable by the key — even with shift modifiers or an ASCII capable keyboard layout. See the following rules for details:

+ +
    +
  1. If the system is Windows and the native keycode of the pressed key indicates that the key is a-z or 0-9, use a keycode for it.
  2. +
  3. If the system is Mac and the native keycode of the pressed key indicates that the key is 0-9, use a keycode for it.
  4. +
  5. If the pressed key inputs an ASCII alphabetic or numeric character with no modifier key, use a keycode for it.
  6. +
  7. If the pressed key inputs an ASCII alphabetic or numeric character with a Shift key modifier, use a keycode for it.
  8. +
  9. If the pressed key inputs a different ASCII character with no modifier key, use a keycode for it.
  10. +
  11. If the pressed key inputs a different ASCII character with a Shift key modifier, use a keycode for it.
  12. +
  13. Otherwise, i.e., pressed key inputs a unicode character: +
      +
    1. If the keyboard layout is ASCII-capable (i.e., can input ASCII alphabets), use 0 or compute with the following additional rules.
    2. +
    3. Otherwise, i.e., the keyboard layout isn't ASCII capable, use the ASCII capable keyboard layout installed on the environment with the highest priority: +
        +
      1. If the pressed key on the alternative keyboard layout inputs an ASCII alphabetic or numeric character, use a keycode for it.
      2. +
      3. Otherwise, use 0 or compute with the following additional rules.
      4. +
      +
    4. +
    +
  14. +
+ +

Starting in Firefox 60 {{geckoRelease("60.0")}}, Gecko sets keyCode values of punctuation keys as far as possible (when points 7.1 or 7.2 in the above list are reached) with the following rules:

+ +
+

The purpose of these new additional rules is for making users whose keyboard layouts map unicode characters to punctuation keys in a US keyboard layout can use web applications which support Firefox only with ASCII-capable keyboard layouts or just with a US keyboard layout. Otherwise, the newly mapped keyCode values may be conflict with other keys. For example, if the active keyboard layout is Russian, the keyCode value of both the "Period" key and "Slash" key are 190 (KeyEvent.DOM_VK_PERIOD). If you need to distinguish those keys but you don't want to support all keyboard layouts in the world by yourself, you should probably use {{domxref("KeyboardEvent.code")}}.

+
+ +
    +
  1. If running macOS or Linux: +
      +
    1. If the active keyboard layout is not ASCII-capable and an alternative ASCII-capable keyboard layout is available. +
        +
      1. If the alternative ASCII-capable keyboard layout produces an ASCII character via just the unmodified key, use a keyCode for the character.
      2. +
      3. If the alternative ASCII-capable keyboard layout produces an ASCII character with a Shift key modifier, use a keyCode for the shifted character.
      4. +
      5. Otherwise, use a keyCode for an ASCII character produced by the key when the US keyboard layout is active.
      6. +
      +
    2. +
    3. Otherwise, use a keyCode for an ASCII character produced by the key when the US keyboard layout is active.
    4. +
    +
  2. +
  3. If running on Windows: +
      +
    1. Use a keyCode value for an ASCII character produced by a key which is mapped to the same virtual keycode of Windows when the US keyboard layout is active.
    2. +
    +
  4. +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
keyCode values of each browser's keydown event caused by printable keys in standard position
{{domxref("KeyboardEvent.code")}}Internet Explorer 11Google Chrome 34Chromium 34Safari 7Gecko 29
WindowsWindowsMac (10.9)Linux (Ubuntu 14.04)Mac (10.9)WindowsMac (10.9)Linux (Ubuntu 14.04)
USJapaneseGreekUSJapaneseGreekUSJapaneseGreekUSJapaneseGreekUSJapaneseGreekUSJapaneseGreekUSJapaneseGreekUSJapaneseGreek
{{domxref("KeyboardEvent.code")}}USJapaneseGreekUSJapaneseGreekUSJapaneseGreekUSJapaneseGreekUSJapaneseGreekUSJapaneseGreekUSJapaneseGreekUSJapaneseGreek
WindowsWindowsMac (10.9)Linux (Ubuntu 14.04)Mac (10.9)WindowsMac (10.9)Linux (Ubuntu 14.04)
Internet Explorer 11Google Chrome 34Chromium 34Safari 7Gecko 29
"Digit1"0x31 (49)0x31 (49)0x31 (49)0x31 (49)0x31 (49)0x31 (49)0x31 (49)0x31 (49)
"Digit2"0x32 (50)0x32 (50)0x32 (50)0x32 (50)0x32 (50)0x32 (50)0x32 (50)0x32 (50)
"Digit3"0x33 (51)0x33 (51)0x33 (51)0x33 (51)0x33 (51)0x33 (51)0x33 (51)0x33 (51)
"Digit4"0x34 (52)0x34 (52)0x34 (52)0x34 (52)0x34 (52)0x34 (52)0x34 (52)0x34 (52)
"Digit5"0x35 (53)0x35 (53)0x35 (53)0x35 (53)0x35 (53)0x35 (53)0x35 (53)0x35 (53)
"Digit6"0x36 (54)0x36 (54)0x36 (54)0x36 (54)0x36 (54)0x36 (54)0x36 (54)0x36 (54)
"Digit7"0x37 (55)0x37 (55)0x37 (55)0x37 (55)0x37 (55)0x37 (55)0x37 (55)0x37 (55)
"Digit8"0x38 (56)0x38 (56)0x38 (56)0x38 (56)0x38 (56)0x38 (56)0x38 (56)0x38 (56)
"Digit9"0x39 (57)0x39 (57)0x39 (57)0x39 (57)0x39 (57)0x39 (57)0x39 (57)0x39 (57)
"Digit0"0x30 (48)0x30 (48)0x30 (48)0x30 (48)0x30 (48)0x30 (48)0x30 (48)0x30 (48)
"KeyA"0x41 (65)0x41 (65)0x41 (65)0x41 (65)0x41 (65)0x41 (65)0x41 (65)0x41 (65)
"KeyB"0x42 (66)0x42 (66)0x42 (66)0x42 (66)0x42 (66)0x42 (66)0x42 (66)0x42 (66)
"KeyC"0x43 (67)0x43 (67)0x43 (67)0x43 (67)0x43 (67)0x43 (67)0x43 (67)0x43 (67)
"KeyD"0x44 (68)0x44 (68)0x44 (68) 0x44 (68)0x44 (68)0x44 (68)0x44 (68)0x44 (68)
"KeyE"0x45 (69)0x45 (69)0x45 (69)0x45 (69)0x45 (69)0x45 (69)0x45 (69)0x45 (69)
"KeyF"0x46 (70)0x46 (70)0x46 (70)0x46 (70)0x46 (70)0x46 (70)0x46 (70)0x46 (70)
"KeyG"0x47 (71)0x47 (71)0x47 (71)0x47 (71)0x47 (71)0x47 (71)0x47 (71)0x47 (71)
"KeyH"0x48 (72)0x48 (72)0x48 (72)0x48 (72)0x48 (72)0x48 (72)0x48 (72)0x48 (72)
"KeyI"0x49 (73)0x49 (73)0x49 (73)0x49 (73)0x49 (73)0x49 (73)0x49 (73)0x49 (73)
"KeyJ"0x4A (74)0x4A (74)0x4A (74)0x4A (74)0x4A (74)0x4A (74)0x4A (74)0x4A (74)
"KeyK"0x4B (75)0x4B (75)0x4B (75)0x4B (75)0x4B (75)0x4B (75)0x4B (75)0x4B (75)
"KeyL"0x4C (76)0x4C (76)0x4C (76)0x4C (76)0x4C (76)0x4C (76)0x4C (76)0x4C (76)
"KeyM"0x4D (77)0x4D (77)0x4D (77)0x4D (77)0x4D (77)0x4D (77)0x4D (77)0x4D (77)
"KeyN"0x4E (78)0x4E (78)0x4E (78)0x4E (78)0x4E (78)0x4E (78)0x4E (78)0x4E (78)
"KeyO"0x4F (79)0x4F (79)0x4F (79)0x4F (79)0x4F (79)0x4F (79)0x4F (79)0x4F (79)
"KeyP"0x50 (80)0x50 (80)0x50 (80)0x50 (80)0x50 (80)0x50 (80)0x50 (80)0x50 (80)
"KeyQ"0x51 (81)0x51 (81)0x51 (81)0x51 (81)0xBA (186)0x51 (81)0x51 (81)0xBA (186)0x51 (81)0x51 (81)0xBA (186)0x51 (81)0x51 (81)0x51 (81)0xBA (186)0x51 (81)
"KeyR"0x52 (82)0x52 (82)0x52 (82)0x52 (82)0x52 (82)0x52 (82)0x52 (82)0x52 (82)
"KeyS"0x53 (83)0x53 (83)0x53 (83)0x53 (83)0x53 (83)0x53 (83)0x53 (83)0x53 (83)
"KeyT"0x54 (84)0x54 (84)0x54 (84)0x54 (84)0x54 (84)0x54 (84)0x54 (84)0x54 (84)
"KeyU"0x55 (85)0x55 (85)0x55 (85)0x55 (85)0x55 (85)0x55 (85)0x55 (85)0x55 (85)
"KeyV"0x56 (86)0x56 (86)0x56 (86)0x56 (86)0x56 (86)0x56 (86)0x56 (86)0x56 (86)
"KeyW"0x57 (87)0x57 (87)0x57 (87)0x57 (87)0x57 (87)0x57 (87)0x57 (87)0x57 (87)
"KeyX"0x58 (88)0x58 (88)0x58 (88)0x58 (88)0x58 (88)0x58 (88)0x58 (88)0x58 (88)
"KeyY"0x59 (89)0x59 (89)0x59 (89)0x59 (89)0x59 (89)0x59 (89)0x59 (89)0x59 (89)
"KeyZ"0x5A (90)0x5A (90)0x5A (90)0x5A (90)0x5A (90)0x5A (90)0x5A (90)0x5A (90)
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
keyCode values of each browser's keydown event caused by printable keys in standard position (punctuations in US layout):
{{domxref("KeyboardEvent.code")}}Internet Explorer 11Google Chrome 34Chromium 34Safari 7Gecko 29
WindowsWindowsMac (10.9)Linux (Ubuntu 14.04)Mac (10.9)Windows (10.9)Mac (10.9)Linux (Ubuntu 14.04)
USJapaneseGreekUSJapaneseGreekUSJapaneseGreekUSJapaneseGreekUSJapaneseGreekUSJapaneseGreekUSJapaneseGreekUSJapaneseGreek
{{domxref("KeyboardEvent.code")}}USJapaneseGreekUSJapaneseGreekUSJapaneseGreekUSJapaneseGreekUSJapaneseGreekUSJapaneseGreekUSJapaneseGreekUSJapaneseGreek
WindowsWindowsMac (10.9)Linux (Ubuntu 14.04)Mac (10.9)WindowsMac (10.9)Linux (Ubuntu 14.04)
Internet Explorer 11Google Chrome 34Chromium 34Safari 7Gecko 29
"Comma"0xBC (188)0xBC (188)0xBC (188)0xBC (188)0xBC (188)0xBC (188)0xBC (188)0xBC (188)
"Comma" with Shift
"Period"0xBE (190)0xBE (190)0xBE (190)0xBE (190)0xBE (190)0xBE (190)0xBE (190)0xBE (190)
"Period" with Shift
"Semicolon"0xBA (186)0xBB (187)0xBA (186)0xBA (186)0xBB (187)0xBA (186)0xBA (186)0xBA (186) *10xE5 (229) *20xBA (186)0xBA (186)0xE5 (229) *30xBA (186)0xBA (186) *10xE5 (229) *20x3B (59)0x3B (59)0x00 (0)0x3B (59)0x3B (59) *10x00 (0)0x3B (59)0x3B (59)0x00 (0)
"Semicolon" with Shift0xBB (187) *10xBB (187)0xBB (187) *1
"Quote"0xDE (222)0xBA (186)0xDE (222)0xDE (222)0xBA (186)0xDE (222)0xDE (222)0xBA (186) *10xDE (222)0xDE (222)0xBA (186)0xDE (222)0xDE (222)0xBA (186)  *10xDE (222)0xDE (222)0x3A (58)0xDE (222)0xDE (222)0x3A (58) *10xDE (222)0xDE (222)0x3A (58)0xDE (222)
"Quote" with Shift0xDE (222) *10x38 (56)0xDE (222) *1
"BracketLeft"0xDB (219)0xC0(192)0xDB (219)0xDB (219)0xC0(192)0xDB (219)0xDB (219)0xDB (219) *10xDB (219)0xDB (219)0x32 (50)0xDB (219)0xDB (219)0xDB (219) *1 0xDB (219)0xDB (219)0x40 (64)0xDB (219)0xDB (219)0x40 (64) *10xDB (219)0xDB (219)0x40 (64)0xDB (219)
"BracketLeft" with Shift0xC0 (192) *10xC0 (192)0xC0 (192) *1
"BracketRight"0xDD (221)0xDB (219)0xDD (221)0xDD (221)0xDB (219)0xDD (221)0xDD (221)0xDB (219) *10xDD (221)0xDD (221)0xDB (219)0xDD (221)0xDD (221)0xDB (219) *10xDD (221)0xDD (221)0xDB (219)0xDD (221)0xDD (221)0xDB (219) *10xDD (221)0xDD (221)0xDB (219)0xDD (221)
"BracketRight" with Shift
"Backquote"0xC0 (192)N/A0xC0 (192)0xC0 (192)N/A0xC0 (192)0xC0 (192)0xC0 (192)0xF4 (244)0xC0 (192)0xC0 (192)0xC0 (192)N/A0xC0 (192)0xC0 (192)0xC0 (192)0x00 (0)0xC0 (192)
"Backquote" with Shift
"Backslash"0xDC (220)0xDD (221)0xDC (220)0xDC (220)0xDD (221)0xDC (220)0xDC (220)0xDC (220)0xDD (221)0xDC (220)0xDC (220)0xDC (220)0xDD (221)0xDC (220)0xDC (220)0xDC (220)0xDD (221)0xDC (220)
"Backslash" with Shift
"Minus"0xBD (189)0xBD (189)0xBD (189)0xBD (189) *10xBD (189)0xBD (189)0xBD (189)0xBD (189)0xBD (189)0xBD (189) *10xBD (189)0xAD (173)0xAD (173)0xAD (173) *10xAD (173)0xAD (173)
"Minus" with Shift0xBB (187) *10xBB (187)0xBD (189)0xBB (187) *10xBD (189)
"Equal"0xBB (187)0xDE (222)0xBB (187)0xBB (187)0xDE (222)0xBB (187)0xBB (187)0xBB (187) *10xBB (187)0xBB (187)0x36 (54)0xBB (187)0xBB (187)0xBB (187) *10xBB (187)0x3D (61)0xA0 (160)0x3D (61)0x3D (61)0xA0 (160) *10x3D (61)0x3D (61)0xA0 (160)0x3D (61)
"Equal" with Shift0xC0 (192) *10xC0 (192)0xBB (187)0xC0 (192) *10xBB (187)
"IntlRo"0xC1 (193)0xE2 (226)0xC1 (193)0xC1 (193)0xE2 (226)0xC1 (193)0xBD (189)0xBD (189)0x00 (0)*40xDC (220)
+  
*40xBD (189)0xBD (189)0xE5 (229) *50x00 (0)0xDC (220)0x00 (0)0xA7 (167)0xA7 (167)0x00 (0)0x00 (0)0xDC (220)0x00 (0)
"IntlRo" with Shift
"IntlYen"0xFF (255)0xDC (220)0xFF (255)0xFF (255)0xDC (220)0xFF (255)0x00 (0)0x00 (0)0x00 (0)*40xDC (220)*40x00 (0)0x00 (0)0xE5 (229) *50x00 (0)0xDC (220)0x00 (0)0xDC (220)0xDC (220)0x00 (0)0x00 (0)0xDC (220)0x00 (0)
"IntlYen" with Shift0xDC (220)0xDC (220)0xBD (189)0xDC (220)0xDC (220)
+ +

*1 The value is input from JIS keyboard. When you use ANSI keyboard, the keyCode value and inputted character are what you select from the US keyboard layout.

+ +

*2 The key is a dead key. The value of keyup event is 0xBA (186).

+ +

*3 The key is a dead key. The value of keyup event is 0x10 (16).

+ +

*4 No key events are fired.

+ +

*5 The key isn't available with Greek keyboard layout (does not input any character). The value of keyup event is 0x00 (0).

+ +

Non-printable keys (function keys)

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
keyCode values of each browser's keydown event caused by modifier keys:
{{domxref("KeyboardEvent.code")}}Internet Explorer 11Google Chrome 34Chromium 34Safari 7Gecko 29
WindowsWindowsMac (10.9)Linux (Ubuntu 14.04)Mac (10.9)WindowsMac (10.9)Linux (Ubuntu 14.04)
{{domxref("KeyboardEvent.code")}}WindowsWindowsMac (10.9)Linux (Ubuntu 14.04)Mac (10.9)WindowsMac (10.9)Linux (Ubuntu 14.04)
Internet Explorer 11Google Chrome 34Chromium 34Safari 7Gecko 29
"AltLeft"0x12 (18)0x12 (18)0x12 (18)0x12 (18)0x12 (18)0x12 (18)0x12 (18)0x12 (18)
"AltRight"0x12 (18)0x12 (18)0x12 (18)0x12 (18)0x12 (18)0x12 (18)0x12 (18)0x12 (18)
"AltRight" when it's "AltGraph" key*1*1N/A0xE1 (225)N/A*1N/A0xE1 (225)
"CapsLock"0x14 (20) *20x14 (20) *20x14 (20)0x14 (20)0x14 (20)0x14 (20) *20x14 (20)0x14 (20) *3
"ControlLeft"0x11 (17)0x11 (17)0x11 (17)0x11 (17)0x11 (17)0x11 (17)0x11 (17)0x11 (17)
"ControlRight"0x11 (17)0x11 (17)0x11 (17)0x11 (17)0x11 (17)0x11 (17)0x11 (17)0x11 (17)
"OSLeft"0x5B (91)0x5B (91)0x5B (91)0x5B (91)0x5B (91)0x5B (91)0xE0 (224)0x5B (91)
"OSRight"0x5C (92)0x5C (92)0x5D (93)0x5C (92)0x5D (93)0x5B (91)0xE0 (224)0x5B (91)
"ShiftLeft"0x10 (16)0x10 (16)0x10 (16)0x10 (16)0x10 (16)0x10 (16)0x10 (16)0x10 (16)
"ShiftRight"0x10 (16)0x10 (16)0x10 (16)0x10 (16)0x10 (16)0x10 (16)0x10 (16)0x10 (16)
+ +

*1 On Windows, "AltGraph" key causes "ControlLeft" key event and "AltRight" key event.

+ +

*2 When Japanese keyboard layout is active, "CapsLock" key without Shift causes 0xF0 (240). The key works as "Alphanumeric" key whose label is "英数".

+ +

*3 When Japanese keyboard layout is active, "CapsLock" key without Shift causes 0x00 (0). The key works as "Alphanumeric" key whose label is "英数".

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
keyCode values of each browser's keydown event caused by non-printable keys:
{{domxref("KeyboardEvent.code")}}Internet Explorer 11Google Chrome 34Chromium 34Safari 7Gecko 29
WindowsWindowsMac (10.9)Linux (Ubuntu 14.04)Mac (10.9)WindowsMac (10.9)Linux (Ubuntu 14.04)
{{domxref("KeyboardEvent.code")}}WindowsWindowsMac (10.9)Linux (Ubuntu 14.04)Mac (10.9)WindowsMac (10.9)Linux (Ubuntu 14.04)
Internet Explorer 11Google Chrome 34Chromium 34Safari 7Gecko 29
"ContextMenu"0x5D (93)0x5D (93)0x00 (0) *10x5D (93)0x00 (0) *10x5D (93)0x5D (93)0x5D (93)
"Enter"0x0D (13)0x0D (13)0x0D (13)0x0D (13)0x0D (13)0x0D (13)0x0D (13)0x0D (13)
"Space"0x20 (32)0x20 (32)0x20 (32)0x20 (32)0x20 (32)0x20 (32)0x20 (32)0x20 (32)
"Tab"0x09 (9)0x09 (9)0x09 (9)0x09 (9)0x09 (9)0x09 (9)0x09 (9)0x09 (9)
"Delete"0x2E (46)0x2E (46)0x2E (46)0x2E (46)0x2E (46)0x2E (46)0x2E (46)0x2E (46)
"End"0x23 (35)0x23 (35)0x23 (35)0x23 (35)0x23 (35)0x23 (35)0x23 (35)0x23 (35)
"Help"N/AN/A0x2D (45) *20x2F (47) *30x2D (45) *2N/A0x2D (45) *20x06 (6) *3
"Home"0x24 (36)0x24 (36)0x24 (36)0x24 (36)0x24 (36)0x24 (36)0x24 (36)0x24 (36)
"Insert"0x2D (45)0x2D (45)0x2D (45)0x2D (45)0x2D (45)0x2D (45)0x2D (45)0x2D (45)
"PageDown"0x22 (34)0x22 (34)0x22 (34)0x22 (34)0x22 (34)0x22 (34)0x22 (34)0x22 (34)
"PageUp"0x21 (33)0x21 (33)0x21 (33)0x21 (33)0x21 (33)0x21 (33)0x21 (33)0x21 (33)
"ArrowDown"0x28 (40)0x28 (40)0x28 (40)0x28 (40)0x28 (40)0x28 (40)0x28 (40)0x28 (40)
"ArrowLeft"0x25 (37)0x25 (37)0x25 (37)0x25 (37)0x25 (37)0x25 (37)0x25 (37)0x25 (37)
"ArrowRight"0x27 (39)0x27 (39)0x27 (39)0x27 (39)0x27 (39)0x27 (39)0x27 (39)0x27 (39)
"ArrowUp"0x26 (38)0x26 (38)0x26 (38)0x26 (38)0x26 (38)0x26 (38)0x26 (38)0x26 (38)
"Escape"0x1B (27)0x1B (27)0x1B (27)0x1B (27)0x1B (27)0x1B (27)0x1B (27)0x1B (27)
"PrintScreen"0x2C (44) *40x2C (44) *40x7C (124)*50x2A (42)0x7C (124)*50x2C (44) *40x2C (44)0x2A (42)
"ScrollLock"0x91 (145)0x91 (145)0x7D (125)*50x91 (145)0x7D (125)*50x91 (145)0x91 (145)0x91 (145)
"Pause"0x13 (19) *60x13 (19) *60x7E (126)*50x13 (19)0x7E (126)*50x13 (19) *60x13 (19)0x13 (19)
+ +

*1 keypress event is fired whose keyCode and charCode are 0x10 (16) but text isn't inputted into editor.

+ +

*2 On Mac, "Help" key is mapped to "Insert" key of PC keyboard. These keyCode values are the same as the "Insert" key's keyCode value.

+ +

*3 Tested on Fedora 20.

+ +

*4 Only keyup event is fired.

+ +

*5 PC's "PrintScreen", "ScrollLock" and "Pause" are mapped to Mac's "F13", "F14" and "F15". Chrome and Safari map same keyCode values with Mac's keys.

+ +

*6 "Pause" key with Control causes 0x03 (3).

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
keyCode values of each browser's keydown event caused by function keys:
{{domxref("KeyboardEvent.code")}}Internet Explorer 11Google Chrome 34Chromium 34Safari 7Gecko 29
WindowsWindowsMac (10.9)Linux (Ubuntu 14.04)Mac (10.9)WindowsMac (10.9)Linux (Ubuntu 14.04)
{{domxref("KeyboardEvent.code")}}WindowsWindowsMac (10.9)Linux (Ubuntu 14.04)Mac (10.9)WindowsMac (10.9)Linux (Ubuntu 14.04)
Internet Explorer 11Google Chrome 34Chromium 34Safari 7Gecko 29
"F1"0x70 (112)0x70 (112)0x70 (112)0x70 (112)0x70 (112)0x70 (112)0x70 (112)0x70 (112)
"F2"0x71 (113)0x71 (113)0x71 (113)0x71 (113)0x71 (113)0x71 (113)0x71 (113)0x71 (113)
"F3"0x72 (114)0x72 (114)0x72 (114)0x72 (114)0x72 (114)0x72 (114)0x72 (114)0x72 (114)
"F4"0x73 (115)0x73 (115)0x73 (115)0x73 (115)0x73 (115)0x73 (115)0x73 (115)0x73 (115)
"F5"0x74 (116)0x74 (116)0x74 (116)0x74 (116)0x74 (116)0x74 (116)0x74 (116)0x74 (116)
"F6"0x75 (117)0x75 (117)0x75 (117)0x75 (117)0x75 (117)0x75 (117)0x75 (117)0x75 (117)
"F7"0x76 (118)0x76 (118)0x76 (118)0x76 (118)0x76 (118)0x76 (118)0x76 (118)0x76 (118)
"F8"0x77 (119)0x77 (119)0x77 (119)0x77 (119)0x77 (119)0x77 (119)0x77 (119)0x77 (119)
"F9"0x78 (120)0x78 (120)0x78 (120)0x78 (120)0x78 (120)0x78 (120)0x78 (120)0x78 (120)
"F10"0x79 (121)0x79 (121)0x79 (121)0x79 (121)0x79 (121)0x79 (121)0x79 (121)0x79 (121)
"F11"0x7A (122)0x7A (122)0x7A (122)0x7A (122)0x7A (122)0x7A (122)0x7A (122)0x7A (122)
"F12"0x7B (123)0x7B (123)0x7B (123)0x7B (123)0x7B (123)0x7B (123)0x7B (123)0x7B (123)
"F13"0x7C (124)0x7C (124)0x7C (124)0x7C (124) *10x7C (124)0x7C (124)0x2C (44) *20x00 (0) *3
"F14"0x7D (125)0x7D (125)0x7D (125)0x7D (125) *10x7D (125)0x7D (125)0x91 (145) *20x00 (0) *3
"F15"0x7E (126)0x7E (126)0x7E (126)0x7E (126) *10x7E (126)0x7E (126)0x13 (19) *20x00 (0) *3
"F16"0x7F (127)0x7F (127)0x7F (127)0x7F (127) *10x7F (127)0x7F (127)0x7F (127)0x00 (0) *3
"F17"0x80 (128)0x80 (128)0x80 (128)0x80 (128) *10x80 (128)0x80 (128)0x80 (128)0x00 (0) *3
"F18"0x81 (129)0x81 (129)0x81 (129)0x81 (129) *10x81 (129)0x81 (129)0x81 (129)0x00 (0) *3
"F19"0x82 (130)0x82 (130)0x82 (130)N/A *40x82 (130)0x82 (130)0x82 (130)0x00 (0) *3
"F20"0x83 (131)0x83 (131)0x83 (131)N/A *40xE5 (229) *50x83 (131)0x00 (0)N/A *6
"F21"0x84 (132)0x84 (132)0x00 (0) *7N/A *40x00 (0) *70x84 (132)N/A *8N/A *6
"F22"0x85 (133)0x85 (133)0x00 (0) *7N/A *40x00 (0) *70x85 (133)N/A *8N/A *6
"F23"0x86 (134)0x86 (134)0x00 (0) *7N/A *40x00 (0) *70x86 (134)N/A *8N/A *6
"F24"0x87 (135)0x87 (135)0x00 (0) *7N/A *40x00 (0) *70x87 (135)N/A *80x00 (0) *3
+ +

*1 Tested on Fedora 20.

+ +

*2 PC's "PrintScreen", "ScrollLock" and "Pause" are mapped to Mac's "F13", "F14" and "F15". Firefox maps same keyCode values with PC's keys.

+ +

*3 Tested on Fedora 20. The keys don't cause GDK_Fxx keysyms. If the keys cause proper keysyms, these values must be same as IE.

+ +

*4 Tested on Fedora 20. The keys don't cause DOM key events on Chromium.

+ +

*5 keyUp event's keyCode value is 0x83 (131).

+ +

*6 Tested on Fedora 20. The keys don't cause DOM key events on Firefox.

+ +

*7 Only keydown event is fired.

+ +

*8 No DOM key events are fired on Firefox.

+ +

Numpad keys

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
keyCode values of each browser's keydown event caused by keys in numpad in NumLock state
{{domxref("KeyboardEvent.code")}}Internet Explorer 11Google Chrome 34Chromium 34Safari 7Gecko 29
WindowsWindowsMac (10.9)Linux (Ubuntu 14.04)Mac (10.9)WindowsMac (10.9)Linux (Ubuntu 14.04)
{{domxref("KeyboardEvent.code")}}WindowsWindowsMac (10.9)Linux (Ubuntu 14.04)Mac (10.9)WindowsMac (10.9)Linux (Ubuntu 14.04)
Internet Explorer 11Google Chrome 34Chromium 34Safari 7Gecko 29
"NumLock"0x90 (144)0x90 (144)0x0C (12) *10x90 (144)0x0C (12) *10x90 (144)0x0C (12) *10x90 (144)
"Numpad0"0x60 (96)0x60 (96)0x60 (96)0x60 (96)0x60 (96)0x60 (96)0x60 (96)0x60 (96)
"Numpad1"0x61 (97)0x61 (97)0x61 (97)0x61 (97)0x61 (97)0x61 (97)0x61 (97)0x61 (97)
"Numpad2"0x62 (98)0x62 (98)0x62 (98)0x62 (98)0x62 (98)0x62 (98)0x62 (98)0x62 (98)
"Numpad3"0x63 (99)0x63 (99)0x63 (99)0x63 (99)0x63 (99)0x63 (99)0x63 (99)0x63 (99)
"Numpad4"0x64 (100)0x64 (100)0x64 (100)0x64 (100)0x64 (100)0x64 (100)0x64 (100)0x64 (100)
"Numpad5"0x65 (101)0x65 (101)0x65 (101)0x65 (101)0x65 (101)0x65 (101)0x65 (101)0x65 (101)
"Numpad6"0x66 (102)0x66 (102)0x66 (102)0x66 (102)0x66 (102)0x66 (102)0x66 (102)0x66 (102)
"Numpad7"0x67 (103)0x67 (103)0x67 (103)0x67 (103)0x67 (103)0x67 (103)0x67 (103)0x67 (103)
"Numpad8"0x68 (104)0x68 (104)0x68 (104)0x68 (104)0x68 (104)0x68 (104)0x68 (104)0x68 (104)
"Numpad9"0x69 (105)0x69 (105)0x69 (105)0x69 (105)0x69 (105)0x69 (105)0x69 (105)0x69 (105)
"NumpadAdd"0x6B (107)0x6B (107)0x6B (107)0x6B (107)0x6B (107)0x6B (107)0x6B (107)0x6B (107)
"NumpadComma" inputting ","0xC2 (194)0xC2 (194)0xBC (188)Always inputs "."0xBC (188)0xC2 (194)0x6C (108)Always inputs "."
"NumpadComma" inputting "." or empty string0xC2 (194)0xC2 (194)0xBE (190)0x6E (110)0xBE (190)0xC2 (194)0x6C (108)0x6E (110)
"NumpadDecimal" inputting "."0x6E (110)0x6E (110)0x6E (110)0x6E (110)0x6E (110)0x6E (110)0x6E (110)0x6E (110)
"NumpadDecimal" inputting ","0x6E (110)0x6E (110)0x6E (110)0x6C (108)0x6E (110)0x6E (110)0x6E (110)0x6C (108)
"NumpadDivide"0x6F (111)0x6F (111)0x6F (111)0x6F (111)0x6F (111)0x6F (111)0x6F (111)0x6F (111)
"NumpadEnter"0x0D (13)0x0D (13)0x0D (13)0x0D (13)0x0D (13)0x0D (13)0x0D (13)0x0D (13)
"NumpadEqual"0x0C (12)0x0C (12)0xBB (187)0xBB (187)0xBB (187)0x0C (12)0x3D (61)0x3D (61)
"NumpadMultiply"0x6A (106)0x6A (106)0x6A (106)0x6A (106)0x6A (106)0x6A (106)0x6A (106)0x6A (106)
"NumpadSubtract"0x6D (109)0x6D (109)0x6D (109)0x6D (109)0x6D (109)0x6D (109)0x6D (109)0x6D (109)
+ +

*1 "NumLock" key works as "Clear" key on Mac.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
keyCode values of each browser's keydown event caused by keys in numpad without NumLock state
{{domxref("KeyboardEvent.code")}}Internet Explorer 11Google Chrome 34Chromium 34Gecko 29
WindowsWindowsLinux (Ubuntu 14.04)WindowsLinux (Ubuntu 14.04)
{{domxref("KeyboardEvent.code")}}WindowsWindowsLinux (Ubuntu 14.04)WindowsLinux (Ubuntu 14.04)
Internet Explorer 11Google Chrome 34Chromium 34Gecko 29
"Numpad0" ("Insert")0x2D (45)0x2D (45)0x2D (45)0x2D (45)0x2D (45)
"Numpad1" ("End")0x23 (35)0x23 (35)0x23 (35)0x23 (35)0x23 (35)
"Numpad2" ("ArrowDown")0x28 (40)0x28 (40)0x28 (40)0x28 (40)0x28 (40)
"Numpad3" ("PageDown")0x22 (34)0x22 (34)0x22 (34)0x22 (34)0x22 (34)
"Numpad4" ("ArrowLeft")0x25 (37)0x25 (37)0x25 (37)0x25 (37)0x25 (37)
"Numpad5"0x0C (12)0x0C (12)0x0C (12)0x0C (12)0x0C (12)
"Numpad6" ("ArrowRight")0x27 (39)0x27 (39)0x27 (39)0x27 (39)0x27 (39)
"Numpad7" ("Home")0x24 (36)0x24 (36)0x24 (36)0x24 (36)0x24 (36)
"Numpad8" ("ArrowUp")0x26 (38)0x26 (38)0x26 (38)0x26 (38)0x26 (38)
"Numpad9" ("PageUp")0x21 (33)0x21 (33)0x21 (33)0x21 (33)0x21 (33)
"NumpadDecimal" ("Delete")0x2E (46)0x2E (46)0x2E (46)0x2E (46)0x2E (46)
+ +

* Recent Mac doesn't have "NumLock" key and state. Therefore, unlocked state isn't available.

+ +

Constants for keyCode value

+ +

Gecko defines a lot of keyCode values in KeyboardEvent for making the mapping table explicitly. These values are useful for add-on developers of Firefox, but not so useful in public web pages.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ConstantValueDescription
DOM_VK_CANCEL0x03 (3)Cancel key.
DOM_VK_HELP0x06 (6)Help key.
DOM_VK_BACK_SPACE0x08 (8)Backspace key.
DOM_VK_TAB0x09 (9)Tab key.
DOM_VK_CLEAR0x0C (12)"5" key on Numpad when NumLock is unlocked. Or on Mac, clear key which is positioned at NumLock key.
DOM_VK_RETURN0x0D (13)Return/enter key on the main keyboard.
DOM_VK_ENTER0x0E (14)Reserved, but not used. {{obsolete_inline(30)}} (Dropped, see {{bug(969247)}}.)
DOM_VK_SHIFT0x10 (16)Shift key.
DOM_VK_CONTROL0x11 (17)Control key.
DOM_VK_ALT0x12 (18)Alt (Option on Mac) key.
DOM_VK_PAUSE0x13 (19)Pause key.
DOM_VK_CAPS_LOCK0x14 (20)Caps lock.
DOM_VK_KANA0x15 (21)Linux support for this keycode was added in Gecko 4.0.
DOM_VK_HANGUL0x15 (21)Linux support for this keycode was added in Gecko 4.0.
DOM_VK_EISU0x 16 (22)"英数" key on Japanese Mac keyboard. {{gecko_minversion_inline("15.0")}}
DOM_VK_JUNJA0x17 (23)Linux support for this keycode was added in Gecko 4.0.
DOM_VK_FINAL0x18 (24)Linux support for this keycode was added in Gecko 4.0.
DOM_VK_HANJA0x19 (25)Linux support for this keycode was added in Gecko 4.0.
DOM_VK_KANJI0x19 (25)Linux support for this keycode was added in Gecko 4.0.
DOM_VK_ESCAPE0x1B (27)Escape key.
DOM_VK_CONVERT0x1C (28)Linux support for this keycode was added in Gecko 4.0.
DOM_VK_NONCONVERT0x1D (29)Linux support for this keycode was added in Gecko 4.0.
DOM_VK_ACCEPT0x1E (30)Linux support for this keycode was added in Gecko 4.0.
DOM_VK_MODECHANGE0x1F (31)Linux support for this keycode was added in Gecko 4.0.
DOM_VK_SPACE0x20 (32)Space bar.
DOM_VK_PAGE_UP0x21 (33)Page Up key.
DOM_VK_PAGE_DOWN0x22 (34)Page Down key.
DOM_VK_END0x23 (35)End key.
DOM_VK_HOME0x24 (36)Home key.
DOM_VK_LEFT0x25 (37)Left arrow.
DOM_VK_UP0x26 (38)Up arrow.
DOM_VK_RIGHT0x27 (39)Right arrow.
DOM_VK_DOWN0x28 (40)Down arrow.
DOM_VK_SELECT0x29 (41)Linux support for this keycode was added in Gecko 4.0.
DOM_VK_PRINT0x2A (42)Linux support for this keycode was added in Gecko 4.0.
DOM_VK_EXECUTE0x2B (43)Linux support for this keycode was added in Gecko 4.0.
DOM_VK_PRINTSCREEN0x2C (44)Print Screen key.
DOM_VK_INSERT0x2D (45)Ins(ert) key.
DOM_VK_DELETE0x2E (46)Del(ete) key.
DOM_VK_00x30 (48)"0" key in standard key location.
DOM_VK_10x31 (49)"1" key in standard key location.
DOM_VK_20x32 (50)"2" key in standard key location.
DOM_VK_30x33 (51)"3" key in standard key location.
DOM_VK_40x34 (52)"4" key in standard key location.
DOM_VK_50x35 (53)"5" key in standard key location.
DOM_VK_60x36 (54)"6" key in standard key location.
DOM_VK_70x37 (55)"7" key in standard key location.
DOM_VK_80x38 (56)"8" key in standard key location.
DOM_VK_90x39 (57)"9" key in standard key location.
DOM_VK_COLON0x3A (58)Colon (":") key. {{gecko_minversion_inline("15.0")}}
DOM_VK_SEMICOLON0x3B (59)Semicolon (";") key.
DOM_VK_LESS_THAN0x3C (60)Less-than ("<") key. {{gecko_minversion_inline("15.0")}}
DOM_VK_EQUALS0x3D (61)Equals ("=") key.
DOM_VK_GREATER_THAN0x3E (62)Greater-than (">") key. {{gecko_minversion_inline("15.0")}}
DOM_VK_QUESTION_MARK0x3F (63)Question mark ("?") key. {{gecko_minversion_inline("15.0")}}
DOM_VK_AT0x40 (64)Atmark ("@") key. {{gecko_minversion_inline("15.0")}}
DOM_VK_A0x41 (65)"A" key.
DOM_VK_B0x42 (66)"B" key.
DOM_VK_C0x43 (67)"C" key.
DOM_VK_D0x44 (68)"D" key.
DOM_VK_E0x45 (69)"E" key.
DOM_VK_F0x46 (70)"F" key.
DOM_VK_G0x47 (71)"G" key.
DOM_VK_H0x48 (72)"H" key.
DOM_VK_I0x49 (73)"I" key.
DOM_VK_J0x4A (74)"J" key.
DOM_VK_K0x4B (75)"K" key.
DOM_VK_L0x4C (76)"L" key.
DOM_VK_M0x4D (77)"M" key.
DOM_VK_N0x4E (78)"N" key.
DOM_VK_O0x4F (79)"O" key.
DOM_VK_P0x50 (80)"P" key.
DOM_VK_Q0x51 (81)"Q" key.
DOM_VK_R0x52 (82)"R" key.
DOM_VK_S0x53 (83)"S" key.
DOM_VK_T0x54 (84)"T" key.
DOM_VK_U0x55 (85)"U" key.
DOM_VK_V0x56 (86)"V" key.
DOM_VK_W0x57 (87)"W" key.
DOM_VK_X0x58 (88)"X" key.
DOM_VK_Y0x59 (89)"Y" key.
DOM_VK_Z0x5A (90)"Z" key.
DOM_VK_WIN0x5B (91)Windows logo key on Windows. Or Super or Hyper key on Linux. {{gecko_minversion_inline("15.0")}}
DOM_VK_CONTEXT_MENU0x5D (93)Opening context menu key.
DOM_VK_SLEEP0x5F (95)Linux support for this keycode was added in Gecko 4.0.
DOM_VK_NUMPAD00x60 (96)"0" on the numeric keypad.
DOM_VK_NUMPAD10x61 (97)"1" on the numeric keypad.
DOM_VK_NUMPAD20x62 (98)"2" on the numeric keypad.
DOM_VK_NUMPAD30x63 (99)"3" on the numeric keypad.
DOM_VK_NUMPAD40x64 (100)"4" on the numeric keypad.
DOM_VK_NUMPAD50x65 (101)"5" on the numeric keypad.
DOM_VK_NUMPAD60x66 (102)"6" on the numeric keypad.
DOM_VK_NUMPAD70x67 (103)"7" on the numeric keypad.
DOM_VK_NUMPAD80x68 (104)"8" on the numeric keypad.
DOM_VK_NUMPAD90x69 (105)"9" on the numeric keypad.
DOM_VK_MULTIPLY0x6A (106)"*" on the numeric keypad.
DOM_VK_ADD0x6B (107)"+" on the numeric keypad.
DOM_VK_SEPARATOR0x6C (108) 
DOM_VK_SUBTRACT0x6D (109)"-" on the numeric keypad.
DOM_VK_DECIMAL0x6E (110)Decimal point on the numeric keypad.
DOM_VK_DIVIDE0x6F (111)"/" on the numeric keypad.
DOM_VK_F10x70 (112)F1 key.
DOM_VK_F20x71 (113)F2 key.
DOM_VK_F30x72 (114)F3 key.
DOM_VK_F40x73 (115)F4 key.
DOM_VK_F50x74 (116)F5 key.
DOM_VK_F60x75 (117)F6 key.
DOM_VK_F70x76 (118)F7 key.
DOM_VK_F80x77 (119)F8 key.
DOM_VK_F90x78 (120)F9 key.
DOM_VK_F100x79 (121)F10 key.
DOM_VK_F110x7A (122)F11 key.
DOM_VK_F120x7B (123)F12 key.
DOM_VK_F130x7C (124)F13 key.
DOM_VK_F140x7D (125)F14 key.
DOM_VK_F150x7E (126)F15 key.
DOM_VK_F160x7F (127)F16 key.
DOM_VK_F170x80 (128)F17 key.
DOM_VK_F180x81 (129)F18 key.
DOM_VK_F190x82 (130)F19 key.
DOM_VK_F200x83 (131)F20 key.
DOM_VK_F210x84 (132)F21 key.
DOM_VK_F220x85 (133)F22 key.
DOM_VK_F230x86 (134)F23 key.
DOM_VK_F240x87 (135)F24 key.
DOM_VK_NUM_LOCK0x90 (144)Num Lock key.
DOM_VK_SCROLL_LOCK0x91 (145)Scroll Lock key.
DOM_VK_WIN_OEM_FJ_JISHO0x92 (146)An OEM specific key on Windows. This was used for "Dictionary" key on Fujitsu OASYS. {{gecko_minversion_inline("21.0")}}
DOM_VK_WIN_OEM_FJ_MASSHOU0x93 (147)An OEM specific key on Windows. This was used for "Unregister word" key on Fujitsu OASYS. {{gecko_minversion_inline("21.0")}}
DOM_VK_WIN_OEM_FJ_TOUROKU0x94 (148)An OEM specific key on Windows. This was used for "Register word" key on Fujitsu OASYS. {{gecko_minversion_inline("21.0")}}
DOM_VK_WIN_OEM_FJ_LOYA0x95 (149)An OEM specific key on Windows. This was used for "Left OYAYUBI" key on Fujitsu OASYS. {{gecko_minversion_inline("21.0")}}
DOM_VK_WIN_OEM_FJ_ROYA0x96 (150)An OEM specific key on Windows. This was used for "Right OYAYUBI" key on Fujitsu OASYS. {{gecko_minversion_inline("21.0")}}
DOM_VK_CIRCUMFLEX0xA0 (160)Circumflex ("^") key. {{gecko_minversion_inline("15.0")}}
DOM_VK_EXCLAMATION0xA1 (161)Exclamation ("!") key. {{gecko_minversion_inline("15.0")}}
DOM_VK_DOUBLE_QUOTE0xA3 (162)Double quote (""") key. {{gecko_minversion_inline("15.0")}}
DOM_VK_HASH0xA3 (163)Hash ("#") key. {{gecko_minversion_inline("15.0")}}
DOM_VK_DOLLAR0xA4 (164)Dollar sign ("$") key. {{gecko_minversion_inline("15.0")}}
DOM_VK_PERCENT0xA5 (165)Percent ("%") key. {{gecko_minversion_inline("15.0")}}
DOM_VK_AMPERSAND0xA6 (166)Ampersand ("&") key. {{gecko_minversion_inline("15.0")}}
DOM_VK_UNDERSCORE0xA7 (167)Underscore ("_") key. {{gecko_minversion_inline("15.0")}}
DOM_VK_OPEN_PAREN0xA8 (168)Open parenthesis ("(") key. {{gecko_minversion_inline("15.0")}}
DOM_VK_CLOSE_PAREN0xA9 (169)Close parenthesis (")") key. {{gecko_minversion_inline("15.0")}}
DOM_VK_ASTERISK0xAA (170)Asterisk ("*") key. {{gecko_minversion_inline("15.0")}}
DOM_VK_PLUS0xAB (171)Plus ("+") key. {{gecko_minversion_inline("15.0")}}
DOM_VK_PIPE0xAC (172)Pipe ("|") key. {{gecko_minversion_inline("15.0")}}
DOM_VK_HYPHEN_MINUS0xAD (173)Hyphen-US/docs/Minus ("-") key. {{gecko_minversion_inline("15.0")}}
DOM_VK_OPEN_CURLY_BRACKET0xAE (174)Open curly bracket ("{") key. {{gecko_minversion_inline("15.0")}}
DOM_VK_CLOSE_CURLY_BRACKET0xAF (175)Close curly bracket ("}") key. {{gecko_minversion_inline("15.0")}}
DOM_VK_TILDE0xB0 (176)Tilde ("~") key. {{gecko_minversion_inline("15.0")}}
DOM_VK_VOLUME_MUTE0xB5 (181)Audio mute key. {{gecko_minversion_inline("21.0")}}
DOM_VK_VOLUME_DOWN0xB6 (182)Audio volume down key {{gecko_minversion_inline("21.0")}}
DOM_VK_VOLUME_UP0xB7 (183)Audio volume up key {{gecko_minversion_inline("21.0")}}
DOM_VK_COMMA0xBC (188)Comma (",") key.
DOM_VK_PERIOD0xBE (190)Period (".") key.
DOM_VK_SLASH0xBF (191)Slash ("/") key.
DOM_VK_BACK_QUOTE0xC0 (192)Back tick ("`") key.
DOM_VK_OPEN_BRACKET0xDB (219)Open square bracket ("[") key.
DOM_VK_BACK_SLASH0xDC (220)Back slash ("\") key.
DOM_VK_CLOSE_BRACKET0xDD (221)Close square bracket ("]") key.
DOM_VK_QUOTE0xDE (222)Quote (''') key.
DOM_VK_META0xE0 (224)Meta key on Linux, Command key on Mac.
DOM_VK_ALTGR0xE1 (225)AltGr key (Level 3 Shift key or Level 5 Shift key) on Linux. {{gecko_minversion_inline("15.0")}}
DOM_VK_WIN_ICO_HELP0xE3 (227)An OEM specific key on Windows. This is (was?) used for Olivetti ICO keyboard.{{gecko_minversion_inline("21.0")}}
DOM_VK_WIN_ICO_000xE4 (228)An OEM specific key on Windows. This is (was?) used for Olivetti ICO keyboard.{{gecko_minversion_inline("21.0")}}
DOM_VK_WIN_ICO_CLEAR0xE6 (230)An OEM specific key on Windows. This is (was?) used for Olivetti ICO keyboard.{{gecko_minversion_inline("21.0")}}
DOM_VK_WIN_OEM_RESET0xE9 (233)An OEM specific key on Windows. This was used for Nokia/Ericsson's device.{{gecko_minversion_inline("21.0")}}
DOM_VK_WIN_OEM_JUMP0xEA (234)An OEM specific key on Windows. This was used for Nokia/Ericsson's device.{{gecko_minversion_inline("21.0")}}
DOM_VK_WIN_OEM_PA10xEB (235)An OEM specific key on Windows. This was used for Nokia/Ericsson's device.{{gecko_minversion_inline("21.0")}}
DOM_VK_WIN_OEM_PA20xEC (236)An OEM specific key on Windows. This was used for Nokia/Ericsson's device.{{gecko_minversion_inline("21.0")}}
DOM_VK_WIN_OEM_PA30xED (237)An OEM specific key on Windows. This was used for Nokia/Ericsson's device.{{gecko_minversion_inline("21.0")}}
DOM_VK_WIN_OEM_WSCTRL0xEE (238)An OEM specific key on Windows. This was used for Nokia/Ericsson's device.{{gecko_minversion_inline("21.0")}}
DOM_VK_WIN_OEM_CUSEL0xEF (239)An OEM specific key on Windows. This was used for Nokia/Ericsson's device.{{gecko_minversion_inline("21.0")}}
DOM_VK_WIN_OEM_ATTN0xF0 (240)An OEM specific key on Windows. This was used for Nokia/Ericsson's device.{{gecko_minversion_inline("21.0")}}
DOM_VK_WIN_OEM_FINISH0xF1 (241)An OEM specific key on Windows. This was used for Nokia/Ericsson's device.{{gecko_minversion_inline("21.0")}}
DOM_VK_WIN_OEM_COPY0xF2 (242)An OEM specific key on Windows. This was used for Nokia/Ericsson's device.{{gecko_minversion_inline("21.0")}}
DOM_VK_WIN_OEM_AUTO0xF3 (243)An OEM specific key on Windows. This was used for Nokia/Ericsson's device.{{gecko_minversion_inline("21.0")}}
DOM_VK_WIN_OEM_ENLW0xF4 (244)An OEM specific key on Windows. This was used for Nokia/Ericsson's device.{{gecko_minversion_inline("21.0")}}
DOM_VK_WIN_OEM_BACKTAB0xF5 (245)An OEM specific key on Windows. This was used for Nokia/Ericsson's device.{{gecko_minversion_inline("21.0")}}
DOM_VK_ATTN0xF6 (246)Attn (Attention) key of IBM midrange computers, e.g., AS/400. {{gecko_minversion_inline("21.0")}}
DOM_VK_CRSEL0xF7 (247)CrSel (Cursor Selection) key of IBM 3270 keyboard layout. {{gecko_minversion_inline("21.0")}}
DOM_VK_EXSEL0xF8 (248)ExSel (Extend Selection) key of IBM 3270 keyboard layout. {{gecko_minversion_inline("21.0")}}
DOM_VK_EREOF0xF9 (249)Erase EOF key of IBM 3270 keyboard layout. {{gecko_minversion_inline("21.0")}}
DOM_VK_PLAY0xFA (250)Play key of IBM 3270 keyboard layout. {{gecko_minversion_inline("21.0")}}
DOM_VK_ZOOM0xFB (251)Zoom key. {{gecko_minversion_inline("21.0")}}
DOM_VK_PA10xFD (253)PA1 key of IBM 3270 keyboard layout. {{gecko_minversion_inline("21.0")}}
DOM_VK_WIN_OEM_CLEAR0xFE (254)Clear key, but we're not sure the meaning difference from DOM_VK_CLEAR. {{gecko_minversion_inline("21.0")}}
+ +

OEM specific keys on Windows

+ +

On Windows, some values of virtual keycode are defined (reserved) for OEM specific key. They are available for special keys on non-standard keyboard. In other words, some values are used for different meaning by two or more vendors (or hardware).

+ +

Starting Gecko 21 (and older than 15), OEM specific key values are available on the keyCode attribute only on Windows. So they are not useful for usual web applications. They are useful only for intranet applications or in similar situations.

+ +

See "Manufacturer-specific Virtual-Key Codes (Windows CE 5.0)" in MSDN for the detail.

+ +
 
diff --git a/files/de/web/api/l10n.language.direction/index.html b/files/de/web/api/l10n.language.direction/index.html new file mode 100644 index 0000000000..c469794d54 --- /dev/null +++ b/files/de/web/api/l10n.language.direction/index.html @@ -0,0 +1,63 @@ +--- +title: L10n.language.direction +slug: Web/API/L10n.language.direction +translation_of: Archive/B2G_OS/API/L10n/language/direction +--- +
{{ non-standard_header() }}
+ +
 
+ +
+

The language.direction property returns the direction (ltr or rtl) of the currently active language.

+
+ +

Syntax

+ +
var languageCode = navigator.mozL10n.language.direction;
+ +

Value

+ +

Returns the direction of the currently active language (ltr or rtl).

+ +

Example

+ +
navigator.mozL10n.ready(function() {
+  console.log('The current language's direction is ' + navigator.mozL10n.language.direction);
+});
+
+ +

Specification

+ +

Not part of any specification.

+ +

See also

+ + + + diff --git a/files/de/web/api/linkstyle/index.html b/files/de/web/api/linkstyle/index.html new file mode 100644 index 0000000000..1cc73d12ac --- /dev/null +++ b/files/de/web/api/linkstyle/index.html @@ -0,0 +1,56 @@ +--- +title: LinkStyle +slug: Web/API/LinkStyle +tags: + - API + - CSSOM + - Referenz + - Schnittstelle +translation_of: Web/API/LinkStyle +--- +

{{APIRef("CSSOM")}}

+ +

Übersicht

+ +

Die LinkStyle Schnittstelle erlaubt es, das zu einem Knoten zugehöriges CSS Stylesheet anzusprechen.

+ +

LinkStyle ist eine abstrakte Schnittstelle und es kann kein Objekt dieses Typs erstellt werden; Sie wird von {{domxref("HTMLLinkElement")}} und {{domxref("HTMLStyleElement")}} Objekten implementiert.

+ +

Eigenschaften

+ +

Es gibt keine vererbte Eigenschaft.

+ +
+
{{domxref("LinkStyle.sheet")}} {{readonlyInline}}
+
Gibt das {{domxref("StyleSheet")}} Objekt zurück, das zu dem angegebenen Element gehört, oder null, falls keines existiert.
+
+ +

Methoden

+ +

Diese Schnittstelle implementiert keine Methoden.

+ +

Spezifikationen

+ + + + + + + + + + + + + + + + + + + +
SpezifikationStatusAnmerkung
{{ SpecName('CSSOM', '#the-linkstyle-interface', 'LinkStyle') }}{{ Spec2('CSSOM') }}Keine Änderung bezüglich {{ SpecName('DOM2 Style') }}.
{{ SpecName('DOM2 Style', 'stylesheets.html#StyleSheets-LinkStyle', 'LinkStyle') }}{{ Spec2('DOM2 Style') }}Ursprüngliche Definition
+ +

Browser Kompatibilität

+ +

 

diff --git a/files/de/web/api/messageevent/index.html b/files/de/web/api/messageevent/index.html new file mode 100644 index 0000000000..5f3bc4c4c8 --- /dev/null +++ b/files/de/web/api/messageevent/index.html @@ -0,0 +1,205 @@ +--- +title: MessageEvent +slug: Web/API/MessageEvent +tags: + - API + - Channels + - Interface + - Nachrichten + - Referenz + - WebSockets + - Window + - Workers + - messaging +translation_of: Web/API/MessageEvent +--- +
{{APIRef("HTML DOM")}}
+ +

Das MessageEvent Interface representiert eine Nachricht die von einem Zielobjekt empfangen wurde.

+ +

Es wird verwendet in in:

+ + + +

Welche Aktion durch dieses Event ausgeführt wird, entscheidet die Funktion die als entsprechender Eventhandler für das {{event("message")}} Event definiert wurde. Beispielsweise durch das setzen eines onmessage handlers. 

+ +

{{AvailableInWorkers}}

+ +

Constructor

+ +
+
{{domxref("MessageEvent.MessageEvent", "MessageEvent()")}}
+
Creates a new MessageEvent.
+
+ +

Eigenschaften

+ +

Dieses Interface erbt auch Eigenschaften seines parents, {{domxref("Event")}}.

+ +
+
{{domxref("MessageEvent.data")}} {{readonlyInline}}
+
Die Daten die vom message emitter gesendet wurden.
+
{{domxref("MessageEvent.origin")}} {{readonlyInline}}
+
Ein {{domxref("USVString")}} der den Ursprung (Origin) des message emitters repräsentiert.
+
{{domxref("MessageEvent.lastEventId")}} {{readonlyInline}}
+
Ein {{domxref("DOMString")}} der die einzigartige ID des Events repräsentiert.
+
{{domxref("MessageEvent.source")}} {{readonlyInline}}
+
Eine MessageEventSource (welch ein {{domxref("WindowProxy")}}, {{domxref("MessagePort")}}, or {{domxref("ServiceWorker")}} Objekt sein kann) welche den message emitter repräsentiert.
+
{{domxref("MessageEvent.ports")}} {{readonlyInline}}
+
Ein Array bestehend aus {{domxref("MessagePort")}} Objekten, welche die Ports repräsentieren, welche mit dem channel verbunden sind durch die die Nachricht gesendet wurde (Bespielsweise in channel messaging oder wenn eine Nachricht zu einem shared worker gesendet wird).
+
+ +

Methoden

+ +

Dieses Interface erbt auch Methoden von seinem parent, {{domxref("Event")}}.

+ +
+
{{domxref("MessageEvent.initMessageEvent()")}} {{deprecated_inline}}
+
Initialisiert ein Message Objekt. Bitte nicht mehr benutzen — benutzen Sie bitte den {{domxref("MessageEvent.MessageEvent", "MessageEvent()")}} constructor stattdessen.
+
+ +

Examples

+ +

In unserem  Grundlegenden Shared Worker Beispiel (Shared Worker ausführen), haben wir zwei HTML Seiten, von denen jede eine einfache Berechnung ausführt. Die unterschiedlichen Skripte benutzen die gleiche Worker Datei um die Berechnungen auszuführen — sie können beide darauf zugreifen, selbst wenn sich ihre Seiten in verschiedenen Fenstern befinden.

+ +

Der folgende Ausschnitt zeigt wie man ein SharedWorker Objekt mit dem {{domxref("SharedWorker.SharedWorker", "SharedWorker()")}} constructor erzeugen kann. Beide Skripte enthalten dies:

+ +
var myWorker = new SharedWorker('worker.js');
+
+ +

Beide Skripte greifen durch ein {{domxref("MessagePort")}} Objekt auf den Worker zu, welcher mit der {{domxref("SharedWorker.port")}} Eigenschaft erstellt wurde. Wenn das onmessage event mittels addEventListener hinzugefügt wird, wird der port automatisch mittels seiner start() Methode gestartet:

+ +
myWorker.port.start();
+ +

Wenn der Port gestartet wurde, senden beide Skripte Nachrichten zu dem Worker und verarbeiten die Nachrichten welche vom Worker empfangen werden mittels  port.postMessage() und port.onmessage:

+ +
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');
+}
+ +

In dem Worker benutzen wir den {{domxref("SharedWorkerGlobalScope.onconnect")}} Handler um uns mit dem oben erwähnten Port zu verbinden. Die mit dem Worker verbundenen Ports sind durch die ports Eigenschaft des {{event("connect")}} Events erreichbar — dann benutzen wir die {{domxref("MessagePort")}} start() Methode um den Port zu starten, und den onmessage Handler um die Nachrichten die von den Hauptthreads gesendet wurden zu verarbeiten.

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

Specifikationen

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "#messageevent", "MessageEvent")}}{{Spec2('HTML WHATWG')}} 
+ +

Browserkompatibilität

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Grundlegende Unterstützung1{{CompatVersionUnknown}}{{CompatGeckoDesktop("2.0")}}9{{CompatUnknown}}{{CompatSafari('10.0+')}}
origin als {{domxref("USVString")}} und source als MessageEventSource{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatGeckoDesktop("55.0")}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Grundlegende Unterstützung{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}3.0+
origin als {{domxref("USVString")}} und source als MessageEventSource{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile("55.0")}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

Siehe auch

+ + diff --git a/files/de/web/api/mouseevent/index.html b/files/de/web/api/mouseevent/index.html new file mode 100644 index 0000000000..55d458c6a2 --- /dev/null +++ b/files/de/web/api/mouseevent/index.html @@ -0,0 +1,323 @@ +--- +title: MouseEvent +slug: Web/API/MouseEvent +tags: + - API + - DOM + - DOM Events + - Interface + - Reference +translation_of: Web/API/MouseEvent +--- +

{{APIRef("DOM Events")}}

+ +

Die MouseEvent Schnittstelle stellt Events bereit, die während der Benutzerinteraktion mit einem Zeigegerät (zum Beispiel eine Maus) auftreten. Häufige Events, die diese Schnittstelle nutzen sind {{event("click")}}, {{event("dblclick")}}, {{event("mouseup")}}, {{event("mousedown")}}.

+ +

MouseEvent wird vererbt von {{domxref("UIEvent")}}, welches wiederum vererbt wird von {{domxref("Event")}}. Obwohl die {{domxref("MouseEvent.initMouseEvent()")}} Methode wegen der Rückwärtskompatibilität bleibt, sollte das Erstellen eines MouseEvent Objekts durch den {{domxref("MouseEvent.MouseEvent", "MouseEvent()")}} Konstruktor erfolgen.

+ +

Mehrere spezifischere Events basieren auf MouseEvent, davon {{domxref("WheelEvent")}} und {{domxref("DragEvent")}}.

+ +

Konstruktor

+ +
+
{{domxref("MouseEvent.MouseEvent", "MouseEvent()")}}
+
Erstellt einMouseEvent Objekt.
+
+ +

Eigenschaften

+ +

Diese Schnittstelle erbt Eigenschaften der Elternobjekte {{domxref("UIEvent")}} und {{domxref("Event")}}.

+ +
+
{{domxref("MouseEvent.altKey")}} {{readonlyinline}}
+
Gibt true zurück wenn die alt Taste gedrückt war, während das MouseEvent ausgelöst wurde.
+
{{domxref("MouseEvent.button")}} {{readonlyinline}}
+
Die Nummer des Buttons der gedrückt wurde (wenn anwendbar), während das MouseEvent ausgelöst wurde.
+
{{domxref("MouseEvent.buttons")}} {{readonlyinline}} {{gecko_minversion_inline("15.0")}}
+
+

Die Buttons, die losgelassen wurden (sofern vorhanden) während das MouseEvent ausgelöst wurde.

+
+
{{domxref("MouseEvent.clientX")}} {{readonlyinline}}
+
Die x-Koordinate des Mauszeigers in lokalen (DOM Inhalt) Koordinaten.
+
{{domxref("MouseEvent.clientY")}} {{readonlyinline}}
+
Die y-Koordinate des Mauszeigers in lokalen (DOM Inhalt) Koordinaten.
+
{{domxref("MouseEvent.ctrlKey")}} {{readonlyinline}}
+
Gibt true zurück, wenn die control Taste gedrückt war, während das MouseEvent ausgelöst wurde.
+
{{domxref("MouseEvent.metaKey")}} {{readonlyinline}}
+
Gibt true zurück, wenn die meta Taste gedrückt war, während das MouseEvent ausgelöst wurde.
+
{{domxref("MouseEvent.movementX")}} {{readonlyinline}}
+
Die x-Koordinate des Mauszeigers relativ zur Position des letzten {{event("mousemove")}} Events.
+
{{domxref("MouseEvent.movementY")}} {{readonlyinline}}
+
Die y-Koordinate des Mauszeigers relativ zur Position des letzten {{event("mousemove")}} Events.
+
{{domxref("MouseEvent.offsetX")}} {{readonlyinline}}{{experimental_inline}}
+
Die x-Koordinate des Mauszeigers relativ zur Position zur padding-Kante des Zielknotens.
+
{{domxref("MouseEvent.offsetY")}} {{readonlyinline}}{{experimental_inline}}
+
Die y-Koordinate des Mauszeigers relativ zur Position zur padding-Kante des Zielknotens.
+
{{domxref("MouseEvent.pageX")}} {{readonlyinline}}{{experimental_inline}}
+
Die x-Koordinate des Mauszeigers relativ zum gesamten Dokument.
+
{{domxref("MouseEvent.pageY")}} {{readonlyinline}}{{experimental_inline}}
+
Die y-Koordinate des Mauszeigers relativ zum gesamten Dokument.
+
{{domxref("MouseEvent.region")}} {{readonlyinline}}
+
Gibt die id des Trefferbereichs wieder, die von dem Event betroffen ist. Wenn kein Trefferbereich betroffen ist, wird null zurückgegeben.
+
{{domxref("MouseEvent.relatedTarget")}} {{readonlyinline}}
+
+

Das sekundäre Zielobjekt des Events, sofern verfügbar.

+
+
{{domxref("MouseEvent.screenX")}} {{readonlyinline}}
+
Die x-Koordinate des Mauszeigers in globalen (Bildschirm) Koordinaten.
+
{{domxref("MouseEvent.screenY")}} {{readonlyinline}}
+
Die y-Koordinate des Mauszeigers in globalen (Bildschirm) Koordinaten.
+
{{domxref("MouseEvent.shiftKey")}} {{readonlyinline}}
+
Gibt true zurück, wenn die shift Taste gedrückt war, während das MouseEvent ausgelöst wurde.
+
{{domxref("MouseEvent.which")}} {{non-standard_inline}} {{readonlyinline}}
+
Der Button, der gedrückt war, als das MouseEvent ausgelöst wurde.
+
{{domxref("MouseEvent.mozPressure")}} {{non-standard_inline()}} {{readonlyinline}}
+
Die Stärke des Drucks, die auf ein Touch- oder Tabletgerät ausgeübt wurde, während das Event ausgelöst wurde. Der Wert bewegt sich zwischen 0.0 (Minimalste Druckstärke) und 1.0 (Maximalster Druckstärke)
+
{{domxref("MouseEvent.mozInputSource")}} {{non-standard_inline()}} {{readonlyinline}}
+
+

Der Typ des Geräts das den Event generiert hat (eine der MOZ_SOURCE_* Konstanten die weiter unten gelistet werden). Es ermöglicht zum Beispiel die Bestimmung ob ein MouseEvent tatsächlich von einer Maus oder von einem Touchgerät ausgelöst wurde (welches den Grad der Genauigkeit beeinflusst, mit dem man die Koordinaten des Events betrachten kann).

+
+
{{domxref("MouseEvent.webkitForce")}} {{non-standard_inline()}} {{readonlyinline}}
+
Die Stärke des Drucks, die beim Klick angewendet wurde.
+
{{domxref("MouseEvent.x")}} {{experimental_inline}}{{readonlyinline}}
+
Alias auf {{domxref("MouseEvent.clientX")}}.
+
{{domxref("MouseEvent.y")}} {{experimental_inline}}{{readonlyinline}}
+
Alias auf {{domxref("MouseEvent.clientY")}}
+
+ +

Konstanten

+ +
+
{{domxref("MouseEvent.WEBKIT_FORCE_AT_MOUSE_DOWN")}} {{non-standard_inline}}{{readonlyinline}}
+
Minimum der Kraft, die für einen normalen Klick notwendig ist.
+
{{domxref("MouseEvent.WEBKIT_FORCE_AT_FORCE_MOUSE_DOWN")}} {{non-standard_inline}}{{readonlyinline}}
+
Minimum der Kraft, die für einen Force-Click notwendig ist.
+
+ +

Methoden

+ +

Das Interface erbt auch die Methoden seiner Eltern, {{domxref("UIEvent")}} und {{domxref("Event")}}.

+ +
+
{{domxref("MouseEvent.getModifierState()")}}
+
Gibt den aktuellen Zustand der angegebenen Modifizierungstaste zurück. Für Detailinformationen siehe {{domxref("KeyboardEvent.getModifierState()")}}.
+
{{domxref("MouseEvent.initMouseEvent()")}} {{deprecated_inline}}
+
Initialisiert den Wert eines erzeugten MouseEvent. Wenn der Event bereits ausgesendet wurde, wird durch diese Methode nichts passieren.
+
+ +

Beispiele

+ +

Dieses Beispiel demonstriert das Simulieren eines Klicks (die programmatische Erzeugung eines Klickereignisses) auf eine Checkbox mittels DOM Methoden. 

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

Auf den Button klicken, um zu sehen wie das Beispiel funktioniert:

+ +

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

+ +

Spezifikationen

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSSOM View','#extensions-to-the-mouseevent-interface', 'MouseEvent')}}{{Spec2('CSSOM View')}}Redefines MouseEvent from long to double. This means that a PointerEvent whose pointerType is mouse will be a double.
{{SpecName("HTML WHATWG", "#dom-mouseevent-region", "MouseEvent.region")}}{{Spec2('HTML WHATWG')}}From {{SpecName('DOM3 Events')}}, added the region property.
{{SpecName('Pointer Lock','#extensions-to-the-mouseevent-interface','MouseEvent')}}{{Spec2('Pointer Lock')}}From {{SpecName('DOM3 Events')}}, added movementX and movementY properties.
{{SpecName('CSSOM View', '#extensions-to-the-mouseevent-interface', 'MouseEvent')}}{{Spec2('CSSOM View')}}From {{SpecName('DOM3 Events')}}, added offsetX and offsetY, pageX and pageY, x, and y properties. Redefined screen, page, client and coordinate (x and y) properties as double from long.
{{SpecName('DOM3 Events','#events-mouseevents','MouseEvent')}}{{Spec2('DOM3 Events')}}From {{SpecName('DOM2 Events')}}, added the MouseEvent() constructor, the getModifierState() method and the buttons property.
{{SpecName('DOM2 Events','#Events-MouseEvent','MouseEvent')}}{{Spec2('DOM2 Events')}}Initial definition.
+ +

Browserkompatibilität

+ +

{{ 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] Setzt das Aktivieren von ExperimentalCanvasFeatures voraus.

+ +

Siehe auch

+ + diff --git a/files/de/web/api/mozmobileconnection/index.html b/files/de/web/api/mozmobileconnection/index.html new file mode 100644 index 0000000000..f4d2882aab --- /dev/null +++ b/files/de/web/api/mozmobileconnection/index.html @@ -0,0 +1,134 @@ +--- +title: MozMobileConnection +slug: Web/API/MozMobileConnection +translation_of: Archive/B2G_OS/API/MozMobileConnection +--- +

{{APIRef("Firefox OS")}} {{ non-standard_header() }}

+ +

{{ B2GOnlyHeader2('certified') }}

+ +
+

This API is used to get information about the current mobile voice and data connection states of the device. It is accessible through {{domxref("window.navigator.mozMobileConnections","navigator.mozMobileConnections")}}, which returns an array of MozMobileConnection objects.

+
+ +
+

Note: The syntax used to be window.navigator.mozMobileConnection, returning a single MozMobileConnection object, but this was updated in Firefox 1.3 due to the introduction of Multi-SIM support (Dual-SIM-Dual-Standby or DSDS).

+
+ +

Interface overview

+ +
callback EventHandler = any (Event event);
+
+interface MozMobileConnection : EventTarget
+{
+  const long ICC_SERVICE_CLASS_VOICE = (1 << 0);
+  const long ICC_SERVICE_CLASS_DATA = (1 << 1);
+  const long ICC_SERVICE_CLASS_FAX = (1 << 2);
+  const long ICC_SERVICE_CLASS_SMS = (1 << 3);
+  const long ICC_SERVICE_CLASS_DATA_SYNC = (1 << 4);
+  const long ICC_SERVICE_CLASS_DATA_ASYNC = (1 << 5);
+  const long ICC_SERVICE_CLASS_PACKET = (1 << 6);
+  const long ICC_SERVICE_CLASS_PAD = (1 << 7);
+  const long ICC_SERVICE_CLASS_MAX = (1 << 7);
+
+  readonly attribute MozMobileConnectionInfo voice;
+  readonly attribute MozMobileConnectionInfo data;
+  readonly attribute DOMString networkSelectionMode;
+  readonly attribute DOMString iccId;
+
+  DOMRequest getNetworks();
+  DOMRequest selectNetwork(MozMobileNetworkInfo network);
+  DOMRequest selectNetworkAutomatically();
+  DOMRequest sendMMI(DOMString mmi);
+  DOMRequest cancelMMI();
+  DOMRequest setCallForwardingOption(MozMobileCFInfo CFInfo);
+  DOMRequest getCallForwardingOption(unsigned short reason);
+
+  attribute EventHandler onvoicechange;
+  attribute EventHandler ondatachange;
+  attribute EventHandler onussdreceived;
+  attribute EventHandler ondataerror;
+  attribute EventHandler oncfstatechange;
+};
+
+ +

Properties

+ +
+
 
+
{{domxref("MozMobileConnection.voice")}} {{readonlyinline}}
+
A {{domxref("MozMobileConnectionInfo")}} object that gives access to information about the voice connection.
+
{{domxref("MozMobileConnection.data")}} {{readonlyinline}}
+
A {{domxref("MozMobileConnectionInfo")}} object that gives access to information about the data connection.
+
{{domxref("MozMobileConnection.iccId")}} {{readonlyinline}}
+
A string that indicates the Integrated Circuit Card Identifier of the SIM this mobile connection corresponds to.
+
{{domxref("MozMobileConnection.networkSelectionMode")}} {{readonlyinline}}
+
A string that indicates the selection mode of the voice and data networks.
+
{{domxref("MozMobileConnection.oncfstatechange")}}
+
A handler for the {{event("cfstatechange")}} event. This event is fired when the call forwarding state changes.
+
{{domxref("MozMobileConnection.ondatachange")}}
+
A handler for the {{event("datachange")}} event. This event is fired whenever the {{domxref("MozMobileConnection.data","data")}} connection object changes values.
+
{{domxref("MozMobileConnection.ondataerror")}}
+
A handler for the {{event("dataerror")}} event. This event is fired whenever the {{domxref("MozMobileConnection.data","data")}} connection object receive an error from the RIL.
+
{{domxref("MozMobileConnection.onussdreceived")}}
+
A handler for the {{event("ussdreceived")}} event. This event is fired whenever a new USSD message is received.
+
{{domxref("MozMobileConnection.onvoicechange")}}
+
A handler for the {{event("voicechange")}} event. This event is fired whenever the {{domxref("MozMobileConnection.voice","voice")}} connection object changes.
+
+ +

Constants

+ + + +

Methods

+ +
+

Note: All original methods from the MozMobileConnection interface are fully asynchronous. They all return a {{domxref("DOMRequest")}} which has a onsuccess and onerror event handler to handle the success or failur of the method call.

+
+ +
+
{{domxref("MozMobileConnection.cancelMMI()")}}
+
Cancel the current MMI request if one exists.
+
{{domxref("MozMobileConnection.getCallForwardingOption()")}}
+
Queries current call forward options.
+
{{domxref("MozMobileConnection.getNetworks()")}}
+
Search for available networks.
+
{{domxref("MozMobileConnection.selectNetwork()")}}
+
Manually selects a network, overriding the radio's current selection.
+
{{domxref("MozMobileConnection.selectNetworkAutomatically()")}}
+
Tell the radio to automatically select a network.
+
{{domxref("MozMobileConnection.sendMMI()")}}
+
Send a MMI message.
+
{{domxref("MozMobileConnection.setCallForwardingOption()")}}
+
Configures call forward options.
+
+ +

The MozMobileConnection interface also inherit from the {{domxref("EventTarget")}} interface

+ +

{{page("/en-US/docs/DOM/EventTarget","Methods")}}

+ +

Specification

+ +

Not part of any specification

+ +

See also

+ + diff --git a/files/de/web/api/mozmobileconnection/selectnetworkautomatically/index.html b/files/de/web/api/mozmobileconnection/selectnetworkautomatically/index.html new file mode 100644 index 0000000000..242901b1c2 --- /dev/null +++ b/files/de/web/api/mozmobileconnection/selectnetworkautomatically/index.html @@ -0,0 +1,57 @@ +--- +title: MozMobileConnection.selectNetworkAutomatically +slug: Web/API/MozMobileConnection/selectNetworkAutomatically +translation_of: Archive/B2G_OS/API/MozMobileConnection/selectNetworkAutomatically +--- +

{{APIRef("Firefox OS")}} {{ non-standard_header() }}

+ +

{{ B2GOnlyHeader2('certified') }}

+ +

Summary

+ +

The selectNetworkAutomatically method is used to tell the radio to automatically select a network.

+ +
+

Note: If the network is actually changed by this request, the voicechange and datachange events are fired.

+
+ +

Syntax

+ +
var request = navigator.mozMobileConnection.selectNetworks();
+ +

Return

+ +

A {{domxref("DOMRequest")}} object to handle the success or failure of the method call.

+ +

If the request fails, the request's error is one of:

+ + + +

Example

+ +
var switchNetwork = navigator.mozMobileConnection.selectNetworkAutomatically();
+
+switchNetwork.onsuccess = function () {
+  console.log('Successful switch');
+}
+
+switchNetwork.onerror = function () {
+  console.log('Unable to switch: ' + this.error.name);
+}
+
+ +

Specification

+ +

Not part of any specification.

+ +

See also

+ + diff --git a/files/de/web/api/mutationobserver/index.html b/files/de/web/api/mutationobserver/index.html new file mode 100644 index 0000000000..c1367cea73 --- /dev/null +++ b/files/de/web/api/mutationobserver/index.html @@ -0,0 +1,287 @@ +--- +title: MutationObserver +slug: Web/API/MutationObserver +tags: + - Beobachter-Muster + - DOM-Knoten + - Fortgeschrittene + - Observer Pattern + - Programmierung + - Wertänderungen verfolgen + - Änderungen überwachen +translation_of: Web/API/MutationObserver +--- +

{{APIRef("DOM")}}

+ +

Der MutationObserver ermöglicht es, auf Änderungen im DOM-Element zu reagieren. Er löst die Mutation Events aus der DOM3 Events Spezifikation ab.

+ +

Konstruktor

+ +

MutationObserver()

+ +

Konstruktor zum Instanziieren neuer DOM-MutationObservers.

+ +
MutationObserver(
+  function callback
+);
+
+ +
Parameters
+ +
+
callback
+
Die Funktion wird bei jeder Veränderung am DOM-Element ausgelöst. Der Observer (Beobachter) ruft die Callbackfunktion mit zwei Argumenten auf. Das erste ist ein Array aus MutationRecord-Objekten. Das zweite ist diese Instanz des MutationObserver.
+
+ +

Methoden

+ + + + + + + + + + + + + +
void observe( {{domxref("Node")}} target, MutationObserverInit options );
void disconnect();
Array takeRecords();
+ +

observe()

+ +

Registriert die Instanz von MutationObserver , um Meldungen über Veränderungen DOM-Elements der angegebenen Node zu erhalten.

+ +
void observe(
+  {{domxref("Node")}} target,
+  MutationObserverInit options
+);
+
+ +
Parameters
+ +
+
target
+
Die {{domxref("Node")}} , zu dem Veränderungen im DOM beobachtet werden sollen.
+
options
+
Ein MutationObserverInit-Objekt, das angibt, welche DOM-Veränderungen gemeldet werden sollen.
+
+ +
Anmerkung: Einen Observer zu einem Element hinzufügen funktioniert genau wie addEventListener - man kann es auch von mehreren Observern gleichzeitig beobachten lassen. Das heißt, wenn man ein Element doppelt beobachtet, feuert es nicht zweimal und man muss auch nicht zweimal disconnect() aufrufen. Mit anderen Worten: wenn man ein Element beobachtet, macht es keinerlei Unterschied, wenn man es durch dasselbe Objekt nochmal beobachten lässt. Wenn es von einem anderen Objekt beobachtet wird, dann wird natürlich zusätzlich ein weiterer Observer angehängt.
+ +

disconnect()

+ +

Sorgt dafür, dass die MutationObserver-Instanz die Überwachung der DOM-Benachrichtigungen beendet. Bis die observe() -Methode erneut benutzt wird, wird die Callback-Methode des Observers nicht aufgerufen.

+ +
void disconnect();
+
+ +

takeRecords()

+ +

Leert die Nachrichten-Kette ("record queue") der MutationObserver Instanz gibt den vorher dort vorhandenen Inhalt zurück.

+ +
Array takeRecords();
+
+ +
Return value
+ +

Gibt ein Array mit MutationRecords zurück.

+ +

MutationObserverInit

+ +

MutationObserverInit ist ein Objekt, das die folgenden Eigenschaften enthalten (und damit festlegen) kann:

+ +
Anmerkung: Als Mindestanforderung muss childList, attributes, oder characterData auf true gesetzt werden. Anderenfalls wird ein Fehler "Ungültiger String angegeben" ("An invalid or illegal string was specified") ausgelöst.
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PropertyDescription
childListWenn Kindelemente (child nodes) der Ziel-Node (inklusive Textnodes) beobachtet werden sollen, muss childList auf true gesetzt werden.
attributesMuss auf true gesetzt werden, wenn Veränderungen an Attributen der Ziel-Node (target node) beobachtet bzw. berichtet werden sollen.
characterData +

Muss true sein, wenn Veränderungen an den Daten der Ziel-Node beobachtet werden sollen.

+
subtreeAuf true setzen, wenn nicht nur Änderungen an der Ziel-Node (target node) beobachtet werden sollen, sondern auch Veränderungen von dessen Kindelementen (child nodes).
attributeOldValueMuss auf true gesetzt werden, wenn attributes ebenfalls true ist und der Wert des target-node-Attributs vor der Veränderung ebenfalls gemeldet werden soll.
characterDataOldValue +

Muss auf true gesetzt werden, wenn characterData ebenfalls true ist und der Wert von data vor der Veränderung ebenfalls gemeldet werden soll.

+
attributeFilterMit dieser Eigenschaft kann ein Array mit lokalen Attributnamen angegeben werden (ohne Namespace), wenn nicht alle Attribute beobachtet werden sollen.
+ +

MutationRecord

+ +

Als erstes Argument wird an die Callback-Funktion des Observers ein Array aus MutationRecord-Objekten übergeben. Ein MutationRecord-Objekt beinhaltet die folgenden Eigenschaften:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PropertyTypeDescription
typeStringGibt attributes zurück, wenn die Veränderung eine Änderung an Attributen der Node gewesen ist, characterData wenn Veränderungen an der CharacterData-Node vorgenommen wurden, und childList wenn es sich um eine Veränderung an den untergeordneten Knoten im Baum handelt.
target{{domxref("Node")}}Gibt die von der Veränderung betroffene Node zurück, abhängig von type. Bei attributes das Element, von dem Attribute geändert wurden. Bei characterData wird die CharacterData-Node zurückgegeben. Bei childList die Node, deren untergeordnete Kindelemente verändert wurden.
addedNodes{{domxref("NodeList")}}Gibt die hinzugefügten Nodes zurück. Wenn keine hinzugefügt wurden, wird eine leere NodeList zurückgegeben.
removedNodes{{domxref("NodeList")}}Gibt die entfernten Nodes zurück. Wenn keine entfernt wurden, wird eine leere NodeList zurückgegeben.
previousSibling{{domxref("Node")}}Gibt den vorhergehenden Sibling der hinzugefügten oder entfernten Node(s) zurück, sonst null.
nextSibling{{domxref("Node")}}Gibt den folgenden Sibling der hinzugefügten oder entfernten Node(s) zurück, sonst null.
attributeNameStringGibt den lokalen Namen des geänderten Attributs zurück, sonst null.
attributeNamespaceStringGibt den lokalen Namespace des geänderten Attributs zurück, sonst null.
oldValueStringRückgabewert hängt vom type ab. Bei attributes wird der Wert des Attributs vor der Änderung zurückgegeben. Bei characterData, der Wert von Data vor der Änderung. Bei childList wird null zurückgegeben.
+ +

Nutzungsbeispiel

+ +

Das folgende Beispiel wurde aus diesem Blog-Post übernommen.

+ +
// zu überwachende Zielnode (target) auswählen
+var target = document.querySelector('#some-id');
+
+// eine Instanz des Observers erzeugen
+var observer = new MutationObserver(function(mutations) {
+  mutations.forEach(function(mutation) {
+    console.log(mutation.type);
+  });
+});
+
+// Konfiguration des Observers: alles melden - Änderungen an Daten, Kindelementen und Attributen
+var config = { attributes: true, childList: true, characterData: true };
+
+// eigentliche Observierung starten und Zielnode und Konfiguration übergeben
+observer.observe(target, config);
+
+// später: Observation wieder einstellen
+observer.disconnect();
+
+ +

Weiterführende Informationen (engl.)

+ + + +

Browserkompatibilität

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support18 {{ property_prefix("WebKit") }}
+ 26
{{ CompatGeckoDesktop(14) }}11156.0 {{ property_prefix("WebKit") }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{ CompatUnknown() }}18 {{ property_prefix("WebKit") }}
+ 26
{{ CompatGeckoMobile(14) }}{{ CompatUnknown() }}15 +

6 {{ property_prefix("WebKit")}}

+ +

7

+
+
diff --git a/files/de/web/api/navigator/index.html b/files/de/web/api/navigator/index.html new file mode 100644 index 0000000000..b6efb42b05 --- /dev/null +++ b/files/de/web/api/navigator/index.html @@ -0,0 +1,122 @@ +--- +title: Navigator +slug: Web/API/Navigator +tags: + - API + - HTML DOM +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/de/web/api/navigator/registerprotocolhandler/index.html b/files/de/web/api/navigator/registerprotocolhandler/index.html new file mode 100644 index 0000000000..2ffd20da9d --- /dev/null +++ b/files/de/web/api/navigator/registerprotocolhandler/index.html @@ -0,0 +1,170 @@ +--- +title: Navigator.registerProtocolHandler() +slug: Web/API/Navigator/registerProtocolHandler +translation_of: Web/API/Navigator/registerProtocolHandler +--- +
{{APIRef("HTML DOM")}}
+ +

In progress. Allows web sites to register themselves as possible handlers for particular protocols.

+ +

For security reasons, by default, web sites may only register protocol handlers for themselves — the domain and protocol of the handler must match the current site. However, users may set a preference in Firefox to allow cross website installation, by setting the gecko.handlerService.allowRegisterFromDifferentHost pref to true in about:config.

+ +

Extensions can register protocol handlers targeting other sites: see the 'See Also' section for how to use them from XPCOM.

+ +

Syntax

+ +
window.navigator.registerProtocolHandler(protocol, url, title);
+
+ +

Parameters

+ +
+
protocol
+
The protocol the site wishes to handle, specified as a string. For example, you can register to handle SMS text message links by registering to handle the "sms" scheme.
+
url
+
The URL of the handler, as a string. This string should include "%s" as a placeholder which will be replaced with the escaped URL of the document to be handled. This URL might be a true URL, or it could be a phone number, email address, or so forth. +
The handler's URL must use one of "http" or "https" as its scheme.
+
+
title
+
A user-readable title string for the protocol handler. This will be displayed to the user in interface objects as needed.
+
+ +

Exceptions

+ +
+
SecurityError
+
The user agent blocked registration of the protocol handler. This might happen if an invalid scheme is specified, such as "http", which cannot be registered for obvious security reasons.
+
SyntaxError
+
The "%s" string is missing from the specified protocol handler URL.
+
+ +

Permitted schemes

+ +

For security reasons, registerProtocolHandler() has restrictions on which schemes may be registered. A custom scheme may be registered as long as the scheme's name begins with "web+", is at least five characters long (including the "web+" prefix), and has only lower-case ASCII letters in its name. For example, "web+burger", as shown in the {{anch("Example")}} below.

+ +

Otherwise, the scheme must be one of the schemes on the whitelist below:

+ +
+ +
+ +

Example

+ +

If your web application is located at http://www.google.co.uk, you can register a protocol handler for it to handle "web+burger" links like this:

+ +
navigator.registerProtocolHandler("web+burger",
+                                  "https://www.google.co.uk/?uri=%s",
+                                  "Burger handler");
+
+ +

This creates a handler that allows web+burger:// links to direct the user to your web application, inserting the burger information specified in the link into the URL. Recall that this script must be run from the same domain (so any page location at google.co.uk) and the second argument passed must be of http or https scheme (in this example it is https) .

+ +

The user will be notified that your code has asked to register the protocol handler, so that they can decide whether or not to permit it. See the screenshot below for an example.

+ +

+ +
+

"Register a webmail service as mailto handler" shows how to do this from XPCOM scope.

+
+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'webappapis.html#dom-navigator-registerprotocolhandler', 'registerProtocolHandler()')}}{{Spec2('HTML WHATWG')}}Initial definition
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support13[1]{{CompatGeckoDesktop("1.9")}}{{CompatUnknown}}11.60{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatGeckoMobile("3.5")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1] Protocol whitelist includes mailto, mms, nntp, rtsp, and webcal. Custom protocols must be prefixed with web+.

+ +

See also

+ + diff --git a/files/de/web/api/navigator/registerprotocolhandler/webbasierte_protokoll-handler/index.html b/files/de/web/api/navigator/registerprotocolhandler/webbasierte_protokoll-handler/index.html new file mode 100644 index 0000000000..5f48e63097 --- /dev/null +++ b/files/de/web/api/navigator/registerprotocolhandler/webbasierte_protokoll-handler/index.html @@ -0,0 +1,127 @@ +--- +title: Webbasierte Protokoll-Handler +slug: Web/API/Navigator/registerProtocolHandler/Webbasierte_protokoll-handler +translation_of: Web/API/Navigator/registerProtocolHandler/Web-based_protocol_handlers +--- +
{{Fx_minversion_header(3)}}
+ +

Hintergrund

+ +

Man findet im Web häufiger Seiten, die Verweise mit anderen Protokollen als HTTP einsetzen. Ein Beispiel ist das mailto: Protokoll:

+ +
+
<a href="mailto:webmaster@example.com">Web Master</a>
+
+ +

Seitenersteller können mailto: Verweise nutzen, wenn sie einen bequemen Weg anbieten möchten, E-Mails direkt aus ihrer Webseite heraus zu versenden. Wird der Link aktiviert, sollte der Browser das im Betriebssystem eingestelle Standardprogramm für E-Mail starten. Das ist ein Beispiel für einen desktopbasierten Protokoll-Handler.

+ +

Webbasierte Protokoll-Handler erlauben webbasierten Anwendungen ebenfall an solchen Prozessen teilzunehmen. Das wird mit der Migration vieler Anwendungen ins Web zunehmend wichtiger. Tatsächlich gibt es bereits viele Webanwendungen, die einen mailto: Verweis verarbeiten könnten.

+ +

Registrierung

+ +

Das Einrichten einer webbasierten Anwendung als Protokoll-Handler ist unkompliziert. Die Webapp nutzt registerProtocolHandler(), um sich selbst beim Browser als potentiellen Handler für ein bestimmtes Protokoll zu registrieren. Ein Beispiel:

+ +
navigator.registerProtocolHandler("burger",
+                                  "http://www.google.co.uk/?uri=%s",
+                                  "Burger handler");
+ +

Die Parameter sind:

+ + + +

Führt ein Browser diesen Code aus, wird er über einen Dialog die Erlaubnis des Nutzers einholen, die Webanwendung als Handler für dieses Protokoll zu registrieren. Firefox zeigt eine Nachricht in der Notification Bar:

+ +

+ +
Hinweis: Das bei der Registrierung angegebene URL Template muss mit der die Anfrage stellenden Webseite übereinstimmen, oder die Registrierung schlägt fehl. Beispielsweise kann http://example.com/homepage.html einen Protokoll-Handler für http://example.com/handle_mailto/%s registrieren, aber nicht für http://example.org/handle_mailto/%s.
+ +

Wird derselbe Handler mehrfach registriert, meldet der Browser das durch ein weiteres Pop-Up, das auf die bereits erfolgte Registrierung hinweist. Daher ist es sinnvoll, die Registrierung mit einem vorangehenden Check abzusichern.

+ +

Beispiel

+ +
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
+<html lang="en">
+<head>
+  <title>Web Protocol Handler Sample - Register</title>
+  <script type="text/javascript">
+    navigator.registerProtocolHandler("burger",
+                                  "http://www.google.co.uk/?uri=%s",
+                                  "Burger handler");
+  </script>
+</head>
+<body>
+  <h1>Web Protocol Handler Sample</h1>
+  <p>This web page will install a web protocol handler for the <code>fake:</code> protocol.</p>
+</body>
+</html>
+
+ +

Aktivierung

+ +

Ab jetzt wird der Browser bei jedem Klick auf einen Verweis, der das neu registrierte Protokoll verwendet, die Ausführung auf die registrierte URL umleiten. Firefox wird zuvor standardmäßig die Bestätigung durch den Nutzer einholen.

+ +

Beispiel

+ +
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
+<html lang="en">
+<head>
+  <title>Web Protocol Handler Sample - Test</title>
+</head>
+<body>
+  <p>Hey have you seen <a href="burger:cheeseburger">this</a> before?</p>
+</body>
+</html>
+
+ +

Handling

+ +

Der nächste Schritt ist das tatsächliche Handling. Der Browser kombiniert die href aus dem aktivierten Link mit dem registrierten URL Template und führt dann damit einen HTTP GET Request aus. Hervorgehend aus den vorangegangenen Beispielen würde der Request auf folgender URL stattfinden:

+ +
http://www.google.co.uk/?uri=burger:cheeseburger
+
+ +

Serverseitiger Code kann dann die query String Parameter extrahieren und die gewünschte Aktion ausführen.

+ +
Hinweis: Dem serverseitigen Code wird der gesamte Inhalt der href übergeben. D.h. der Server muss das Protokoll aus den Daten parsen.
+ +

Beispiel

+ +
<?php
+$value = "";
+if ( isset ( $_GET["value"] ) ) {
+  $value = $_GET["value"];
+}
+?>
+
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
+<html lang="en">
+<head>
+    <title>Web Protocol Handler Sample</title>
+</head>
+<body>
+  <h1>Web Protocol Handler Sample - Handler</h1>
+  <p>This web page is called when handling a <code>burger:</code> protocol action. The data sent:</p>
+  <textarea>
+<?php echo(htmlspecialchars($value, ENT_QUOTES, 'UTF-8')); ?>
+  </textarea>
+</body>
+</html>
+
+ +

Verweise

+ + + +

Siehe auch

+ + diff --git a/files/de/web/api/navigator/sendbeacon/index.html b/files/de/web/api/navigator/sendbeacon/index.html new file mode 100644 index 0000000000..1e8ff5ea2b --- /dev/null +++ b/files/de/web/api/navigator/sendbeacon/index.html @@ -0,0 +1,144 @@ +--- +title: Navigator.sendBeacon() +slug: Web/API/Navigator/sendBeacon +translation_of: Web/API/Navigator/sendBeacon +--- +
{{APIRef("HTML DOM")}}{{SeeCompatTable}}
+ +

Die navigator.sendBeacon() Methode dient dazu, kleinere Datenmengen asynchron per HTTP vom User Agent zum Server zu senden.

+ +

Syntax

+ +
navigator.sendBeacon(url, data);
+
+ +

Parameter

+ +
+
url
+
Der url Parameter steht für die ermittelte URL, an die data zu senden ist. 
+
+ +
+
data
+
Der Parameter data enthält zu übermittelnde Daten der Art {{domxref("ArrayBufferView")}}, {{domxref("Blob")}}, {{domxref("DOMString")}} oder {{domxref("FormData")}}.
+
+ +

Rückgabewerte

+ +

Die sendBeacon() Methode gibt true zurück, falls der User Agent erfolgreich war, data zum Transfer bereit zu stellen. Andernfalls ist der Rückgabewert false.

+ +

Beschreibung

+ +

Diese Methode erfüllt Bedürfnisse von Analyse- und Diagnostik-Code, der regelmäßig versucht, Daten an den Server zu senden bevor der unload Vorgang einer Seite abgeschlossen ist. Daten schon früher zu senden, könnte eine unvollständige Datensammlung bewirken.
+ Bislang war es für Entwickler schwierig, sicherzustellen, dass Daten während eines unload Vorgangs tatsächlich gesendet wurden.

+ +

Üblicherweise ignorieren User Agenten asynchrone XMLHttpRequests in einem unload Anweisungsblock. Dieses Problem wird in Analytik- und Diagnostik-Code oft umgangen, indem in einem unload oder beforeunload Anweisungsblock ein synchroner XMLHttpRequest zum Datenversand genutzt wird.
+ Ein synchroner XMLHttpRequest zwingt den User Agenten den unload Vorgang des Dokuments zu verzögern, sodass jedoch die weitere Navigation langsamer wirkt. Der Eindruck einer schlechten Ladezeit der Folgeseite läst sich dabei nicht verhindern.

+ +

Es gibt weitere Techniken, die Datenübermittlung zu ermöglichen. Eine besteht darin, den unload Vorgang zu verzögern, indem man ein image Element erzeugt und dessen src Attribut innerhalb des unload Anweisungsblocks ändert. Da die meisten User Agenten den unload Vorgang verzögern werden bis das Nachladen des Bildes abgeschlossen ist, können so währenddessen noch Daten übermittelt werden.
+ Noch eine andere Technnik verwendet eine einige Sekunden lange wirkungsfreie (noop) Schleife innerhalb des unload Anweisungsblocks, die das unload verzögert und zwischenzeitliche Datenübermittlung zum Server ermöglicht.

+ +

Diese alternativen Techniken stellen allerdings nicht nur schlechte Programmiermuster dar. Einige sind schlicht unzuverlässig und erzeugen den Eindruck schlechter Seitenladezeiten.

+ +

Das folgende Beispiel zeigt einen fiktiven Analytik-Code, der versucht, Daten an den Server zu schicken mittels synchronem XMLHttpRequest innerhalb des unload Anweisungsblocks. Dies resultiert in einer Verzögerung des unload Vorgangs der Seite.

+ +
window.addEventListener('unload', logData, false);
+
+function logData() {
+    var client = new XMLHttpRequest();
+    client.open("POST", "/log", false); // der dritte Parameter bewirkt synchrones xhr
+    client.setRequestHeader("Content-Type", "text/plain;charset=UTF-8");
+    client.send(analyticsData);
+}
+
+ +

Durch Verwendung der sendBeacon() Methode werden Daten asynchron an den Server gesendet sobald der User Agent Gelegenheit dazu hat und zwar ohne das unload bzw. das Laden der nächsten Seite zu verzögen.

+ +

Das folgende Beispiel zeigt einen fiktiven Analytik-Code, der Daten zum Server sendet mittels sendBeacon()Methode. 

+ +
window.addEventListener('unload', logData, false);
+
+function logData() {
+    navigator.sendBeacon("/log", analyticsData);
+}
+
+ +

Spezifikation

+ + + + + + + + + + + + + + +
SpezifikationStatusKommentar
{{SpecName('Beacon', '#sec-sendBeacon-method', 'sendBeacon()')}}{{Spec2('Beacon')}}Initial definition
+ +

Browser Kompatibilität

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome(39.0)}}{{CompatGeckoDesktop("31")}}{{CompatNo}}26{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatChrome(40.0)}}{{CompatGeckoMobile("31")}}2.5{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatChrome(42.0)}}
+
+ +

Siehe auch

+ + diff --git a/files/de/web/api/navigator/vibrate/index.html b/files/de/web/api/navigator/vibrate/index.html new file mode 100644 index 0000000000..55b453cee1 --- /dev/null +++ b/files/de/web/api/navigator/vibrate/index.html @@ -0,0 +1,107 @@ +--- +title: Navigator.vibrate() +slug: Web/API/Navigator/vibrate +translation_of: Web/API/Navigator/vibrate +--- +

{{APIRef("HTML DOM")}}

+ +

Die Navigator.vibrate()-Methode erzeugt eine Vibration, wenn entsprechende Hardware vorhanden ist. Wenn das Gerät keine Vibration unterstützt, hat diese Methode keine Auswirkungen. Wenn eine Vibration gestartet werden soll, aber eine andere Vibration noch ausgeführt wird, wird die Alte gestoppt und die Neue gestartet!

+ +

Wenn die Methode nicht ausgeführt werden konnte aufgrund eines ungültigen Parameters wird ein false zurückgegeben, ansonsten ein true. Wenn das Modell zu lang ausgeführt wird, wird es abgeschnitten: die maximale Dauer ist je nach Implementierung abhängig!

+ +

Syntax

+ +
var successBool = window.navigator.vibrate(pattern);
+
+ +
+
pattern
+
Bietet ein Schema von Vibrationen und Vibrationsintervallen. Jeder Wert bezeichnet eine Anzahl an Millisekunden zum vibrieren und pausieren (im Wechsel). Sie bieten entweder einen einzelnen Wert (um einmal für so viele Millisekunden zu vibrieren) oder ein Array von Werten, um abwechselnd zu vibrieren, pausieren, dann wieder zu vibrieren. Siehe Vibration API für weitere Details.
+
+ +

Wenn man 0 als Wert, einen leeren Array oder einen Array, der nur 0 als Wert(e) enthält, angibt wird die Vibration gestoppt.

+ +

Beispiele

+ +
window.navigator.vibrate(200); // vibriert 200ms lang
+window.navigator.vibrate([100,30,100,30,100,200,200,30,200,30,200,200,100,30,100,30,100]); // vibriert 'SOS' im Morsecode
+
+ +

Technische Daten

+ + + + + + + + + + + + + + + + +
Technische DatenStatusHinweis
{{SpecName('Vibration API')}}{{Spec2('Vibration API')}}Linked to spec is the latest editor's draft; W3C version is a REC.
+ +

Browser-Kompatibilität

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FunktionChromeFirefox (Gecko)Internet ExplorerOperaSafari
Grundlegende Unterstützung{{CompatVersionUnknown}} {{property_prefix("webkit")}}{{CompatGeckoDesktop("11.0")}} {{property_prefix("moz")}}
+ {{CompatGeckoDesktop("16.0")}} (no prefix) [1]
{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FunktionAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Grundlegende Unterstützung{{CompatVersionUnknown}} {{property_prefix("webkit")}}{{CompatGeckoMobile("11.0")}} {{property_prefix("moz")}}
+ {{CompatGeckoMobile("16.0")}} (no prefix) [1]
{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

[1] Wenn die Vibration zulang ist, das heißt der Wert selbst oder das Muster, wurde bis einschließlich Firefox 26 anstatt  false, eine Fehlermeldung zurückgegeben ({{bug("884935")}}). Ab Firefox 32 wird true zurückgegeben, aber das Muster gekürzt ({{bug(1014581)}}).

+ +

Weitere Informationen

+ + diff --git a/files/de/web/api/navigatoronline/index.html b/files/de/web/api/navigatoronline/index.html new file mode 100644 index 0000000000..11f6707c43 --- /dev/null +++ b/files/de/web/api/navigatoronline/index.html @@ -0,0 +1,127 @@ +--- +title: NavigatorOnLine +slug: Web/API/NavigatorOnLine +tags: + - API + - HTML-DOM + - NeedsTranslation + - TopicStub +translation_of: Web/API/NavigatorOnLine +--- +

{{APIRef("HTML DOM")}}

+ +

The NavigatorOnLine interface contains methods and properties related to the connectivity status of the browser.

+ +

There is no object of type NavigatorOnLine, but other interfaces, like {{domxref("Navigator")}} or {{domxref("WorkerNavigator")}}, implement it.

+ +

Properties

+ +

The NavigatorOnLine interface doesn't inherit any property.

+ +
+
{{domxref("NavigatorOnLine.onLine")}} {{readonlyInline}}
+
Returns a {{domxref("Boolean")}} indicating whether the browser is working online.
+
+ +

Methods

+ +

The NavigatorOnLine interface neither implements, nor inherit any method.

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#navigatoronline', 'NavigatorOnLine')}}{{Spec2('HTML WHATWG')}}No change from the latest snapshot, {{SpecName('HTML5 W3C')}}
{{SpecName('HTML5 W3C', '#navigatoronline', 'NavigatorOnLine')}}{{Spec2('HTML5 W3C')}}Snapshot of {{SpecName('HTML WHATWG')}} with its initial specification.
+ +

Browser compatibility

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
on {{domxref("WorkerNavigator")}}{{CompatUnknown}}{{CompatGeckoDesktop(29)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
on {{domxref("WorkerNavigator")}}{{CompatUnknown}}{{CompatGeckoMobile(29)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

See also

+ + diff --git a/files/de/web/api/navigatoronline/online/index.html b/files/de/web/api/navigatoronline/online/index.html new file mode 100644 index 0000000000..2995101bb4 --- /dev/null +++ b/files/de/web/api/navigatoronline/online/index.html @@ -0,0 +1,190 @@ +--- +title: NavigatorOnLine.onLine +slug: Web/API/NavigatorOnLine/onLine +tags: + - API + - DOM + - Dokumentation + - Eigenschaft + - Navigation + - NavigatorOnLine + - Offline + - Online + - Reference + - WebAPI +translation_of: Web/API/NavigatorOnLine/onLine +--- +
{{ApiRef("HTML DOM")}}
+ +

Diese Eigenschaft gibt einen Wahrheitswert (Bool-Wert) zurück, der Auskunft gibt, ob der Browser eine Internetverbindung aufbauen konnte. Dieser Wert wird immer dann aktualisiert, wenn eine neue Verbindung vom Browser angefordert wurde (durch Script- oder Benutzeraktionen). Es wird "false" zurückgegeben, wenn der letzte Versuch, eine Verbindung aufzubauen, fehlgeschlagen ist.

+ +

Einige Browser implementieren diese Funktion verschieden.

+ +

Für Chrome und Safari gilt, dass wenn keine Verbindung zum LAN oder Router aufgebaut wurde, der Browser "offline" ist. Andernfalls ist der Browser "online". Das bedeutet, dass aus dem Online-Status nicht die tatsächliche Verbindung erkennbar ist. Wenn der Rückgabewert "false" ist, dann ist mit Sicherheit keine Verbindung vorhanden. Wenn der Wert aber "true" ist, muss dies keine tatsächliche Verbindung zum Internet bedeuten. Auch kann die Ausführung innerhalb einer Virtuellen Maschine den Wert verfälschen. Für weitere Informationen kann dieser HTML5-Rocks Artikel hilfreich sein (in Englisch): Working Off the Grid with HTML5 Offline

+ +

Firefox und der Internet Explorer können diesen Wert auch durch die Funktion des "Offline-Modus" verändern. Dann wird auch "false" zurückgegeben, unabhängig vom tatsächlichen Status.

+ +

Bis Firefox 41 wurde in allen anderen Fällen "true" zurückgegeben. Seit Version 41 kann der tatsächliche Verbindungsstatus erkannt werden, wenn Firefox auf OS X oder Windows installiert ist.

+ +

Es sind auch folgende Ereignisse verfügbar, mit denen unmittelbar auf Änderungen des "OnLine"-Wertes reagiert werden kann.

+ + + +

 

+ +

Syntax

+ +
online = window.navigator.onLine;
+
+ +

Value

+ +

Der Rückgabewert ist vom Typ "boolean", kann also true oder false sein.

+ +

 

+ +

Beispiel

+ +

Hier das Live-Beispiel

+ +

Um zu bestimmen, ob der Browser mit dem Internet verbunden ist, müssen Sie den Wert von window.navigator.onLine wie folgt verwenden:

+ +
if (navigator.onLine) {
+  console.log('Verbunden');
+} else {
+  console.log('Getrennt');
+}
+ +

Wenn der Browser onLine nicht kennt, wird false oder undefiniert zurückgegeben.

+ +

Um auf dir Veränderung des Status direkt reagieren zu können, verwenden Sie addEventListener für die Ereignisse window.ononline und window.onoffline; wie in diesem Beispiel:

+ +
window.addEventListener("offline", function(e) { console.log("Nicht Verbunden"); });
+
+window.addEventListener("online", function(e) { console.log("Verbunden"); });
+
+ +

 

+ +

Spezifikationen

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("HTML WHATWG", "browsers.html#navigator.online", "navigator.onLine")}}{{Spec2("HTML WHATWG")}}Initial definition
+ +

 

+ +

Browserkompatibilität

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FunktionChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Einfache Umsetzung{{CompatVersionUnknown}}[1]{{CompatGeckoDesktop(1.9.1)}}[2]
+ {{CompatGeckoDesktop(2.0)}}[4]
8[3]{{CompatNo}}[2]5.0.4
on {{domxref("WorkerNavigator")}}{{CompatUnknown}}{{CompatGeckoDesktop(29)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FunktionAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari MobileBlackBerry
Einfache Umsetzung2.2[5]{{CompatGeckoMobile(1.9.1)}}[2]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}} +

7
+ 10

+
on {{domxref("WorkerNavigator")}}{{CompatUnknown}}{{CompatGeckoMobile(29)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1] Vorherige Versionen von Chrome geben true unmittelbar nach den öffnen des Tabs zurück. Erst nach der nächsten Netzwerkaktivität wird der richtige Wert zurückgegeben.  Windows: 11, Mac: 14, Chrome OS: 13, Linux: Liefert immer true zurück. Siehe auch crbug.com/7469.

+ +

[2] Seit Firefox 4 und Opera 11.10 wird false unabhängig von der tatsächlichen Verbindung zurückgegeben, wenn der "offline"-Modus des Browsers aktiviert wurde. 

+ +

[3] Im Internet Explorer 8 werden die "online"- and "offline"-Ereignisse duch document.body ausgelöst; seit dem IE 9 werden diese auch von window ausgelöst.

+ +

[4] Seit Firefox 41, auf OS X und Windows, wird der tatsächliche Verbindungstatus zurückgegeben, solange der "offline"-Modus nicht aktivert wurde.

+ +

[5] Fehler in der WebView-Komponenten, siehe auch: bug 16760.

+ +

 

+ +

Hinweise

+ +

Für weitere Informationen, siehe auch die  Online/Offline‎-Ereignisse 

+ +

 

+ +

Verweise

+ + diff --git a/files/de/web/api/navigatoronline/online_and_offline_events/index.html b/files/de/web/api/navigatoronline/online_and_offline_events/index.html new file mode 100644 index 0000000000..4bceb46e36 --- /dev/null +++ b/files/de/web/api/navigatoronline/online_and_offline_events/index.html @@ -0,0 +1,120 @@ +--- +title: Online- und Offline-Events +slug: Web/API/NavigatorOnLine/Online_and_offline_events +translation_of: Web/API/NavigatorOnLine/Online_and_offline_events +--- +

Einige Browser implementieren Online-/Offline-Events basierend auf der WHATWG Web Applications 1.0 specification.

+ +

Übersicht

+ +

Um eine gute offlinefähige Webanwendung erstellen zu können, muss die Anwendung wissen, wann sie offline ist. Zusätzlich muss die Anwendung wissen, wann die Internetverbindung wieder verfügbar ist. Die Voraussetzungen sind also:

+ +
    +
  1. die Anwendung erfährt, wann die Verbindung nach einem Verbindungsabbruch wieder besteht, so dass Änderungen mit dem Server abgeglichen werden können
  2. +
  3. die Anwendung erfährt, wann die Verbindung abbricht, um so Serveranfragen für später in eine Warteschlange einreihen zu können
  4. +
+ +

Dieser Vorgang trägt dazu bei, Online-/Offline Ereignisse zu trivialisieren.

+ +

Oft benötigen Webanwendungen außerdem die Möglichkeit, bestimmte Dokumente im Offline-Cache zu halten. Mehr Informationen darüber gibt es unter Offline resources in Firefox.

+ +

API

+ + + +

navigator.onLine ist eine Eigenschaft mit boole'schem Wert (true für online, false für offline). Sie aktualisiert sich, sobald der Benutzer in den Offline-Modus wechselt, indem der entsprechende Menü-Eintrag angewählt wird (in Firefox: Datei -> Offline-Modus).

+ +

Die Eigenschaft aktualisiert sich außerdem, sobald der Browser nicht mehr in der Lage ist, eine Verbindung herzustellen. Gemäß der Spezifikation:

+ +
The navigator.onLine attribute must return false if the user agent will not contact the network when the user follows links or when a script requests a remote page (or knows that such an attempt would fail)...
+ +

Firefox 2 aktualisiert diese Eigenschaft beim Wechseln in den Offline-Modus und zurück, sowie beim Abbruch/Wiederaufbau der Netzwerkverbindung in Windows und Linux.

+ +

Diese Eigenschaft existierte bereits in älteren Versionen von Firefox und Internet Explorer (die Spezifikation selbst basiert auf den vorherigen Implementierungen), sodass man sie schon jetzt einsetzen kann. Die Autoerkennung der Konnektivität wurde in Firefox 2 implementiert.

+ +

"online" und "offline" Events

+ +

Mit Firefox 3 gibt es 2 neue Events: "online" und "offline". Diese werden auf dem <body> jeder Sete ausgelöst, wenn der Browser zwischen Online- und Offline-Modus wechselt. Zusätzlich steigen die Events auf von document.body, zu document, und letztlich zu window. Beide können nicht unterbunden werden (man kann den Benutzer nicht daran hindern, online oder offline zu gehen).

+ +

Die Events können auf bekannte Art und Weise registriert werden:

+ + + +

Beispiel

+ +

Es gibt einen einfachen Test, um zu überprüfen, ob die Events funktionieren:

+ +

Hier ist der JavaScript-Teil:

+ +
window.addEventListener('load', function() {
+  var status = document.getElementById("status");
+
+  function updateOnlineStatus(event) {
+    var condition = navigator.onLine ? "online" : "offline";
+
+    status.className = condition;
+    status.innerHTML = condition.toUpperCase();
+
+    log.insertAdjacentHTML("beforeend", "Event: " + event.type + "; Status: " + condition);
+  }
+
+  window.addEventListener('online',  updateOnlineStatus);
+  window.addEventListener('offline', updateOnlineStatus);
+});
+ +

Ein bißchen CSS:

+ +
#status {
+  position : fixed;
+  width: 100%;
+  font : bold 1em sans-serif;
+  color: #FFF:
+  padding : 0.5em
+}
+
+#log {
+  padding: 2.5em 0.5em 0.5em;
+  font: 1em sans-serif;
+}
+
+.online {
+  background: green;
+}
+
+.offline {
+  background: red;
+}
+
+ +

Und das entsprechende HTML:XXX When mochitests for this are created, point to those instead and update this example -nickolay

+ +
<div id="status"></div>
+<div id="log"></div>
+<p>This is a test</p>
+
+ +

Hier ist das Live-Ergebnis:

+ +

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

+ +

Hinweise

+ +

Wenn die API im Browser nicht implementiert ist, gibt es andere Möglichkeiten herauszufinden, ob der Benutzer offline ist: zum Beispiel durch das Reagieren auf AppCache error Ereignissen oder auf Antworten von XMLHttpRequest.

+ +

Verweise

+ + diff --git a/files/de/web/api/node/appendchild/index.html b/files/de/web/api/node/appendchild/index.html new file mode 100644 index 0000000000..519f6f9a0d --- /dev/null +++ b/files/de/web/api/node/appendchild/index.html @@ -0,0 +1,144 @@ +--- +title: Node.appendChild() +slug: Web/API/Node/appendChild +tags: + - API + - DOM + - Method + - Node + - Reference +translation_of: Web/API/Node/appendChild +--- +
{{APIRef("DOM")}}
+ +

Die Node.appendChild() Methode fügt einen Kind-Knoten am Ende der Liste aller Kinder des angegebenen Eltern-Knotens an (to append = anhängen).

+ +

Wenn das gegebene Kind eine Referenz zu einem existierenden Knoten im Dokument ist, wird appendChild() es von der aktuellen Position zu der neuen Position bewegen. Es gibt also keine Notwendigkeit den Knoten erst zu entfernen, weil ein Knoten in einem Dokument nicht gleichzeitig an zwei Stellen vorkommen kann. Also, wenn der Knoten bereits einen Eltern-Knoten hat, wird der Knoten zuerst entfernt und dann erneut am Ende der Kind-Knoten-Liste angehängt.

+ +

Das {{domxref("Node.cloneNode()")}}  kann genutzt werden um eine Kopie des Knotens zu machen, bevor es an einen neuen Eltern-Knoten angehängt wird. Zu beachten: Kopien die mit cloneNode gemacht wurden, werden nicht automatisch Synchron gehalten.

+ +

Syntax

+ +
var aChild = element.appendChild(aChild);
+ +

Parameter

+ +

aChild

+ +

Der Knoten, der an den gegebenen Eltern-Knoten angehängt wird (für gewöhnlich ein Element).

+ +

Rückgabewert

+ +

Der Rückgabewert ist das angehängte Kindelement (aChild), außer wenn aChild ein {{domxref("DocumentFragment")}} ist. In diesem Fall wird ein {{domxref("DocumentFragment")}} zurückgegeben.

+ +

Anmerkungen

+ +

Eine Verkettung kann anders ablaufen als erwartet, da appendChild() das Kindelement zurück gibt.

+ +
var aBlock = doc.createElement('block').appendChild(doc.createElement('b'));
+ +

Setzt nur aBlock auf <b></b>, was möglicherweise nicht das gewünschte ist.

+ +

Beispiele

+ +
//  Erstellen Sie ein neues Absatz-Element und fügen Sie es an das Ende des Dokument-Körpers (body)
+var p = document.createElement("p");
+document.body.appendChild(p);
+ +

Spezifikationen

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpezifikationStatusKommentar
{{SpecName('DOM WHATWG', '#dom-node-appendchild', 'Node.appendChild()')}}{{Spec2('DOM WHATWG')}}No change from {{SpecName("DOM3 Core")}}.
{{SpecName('DOM3 Core', 'core.html#ID-184E7107', 'Node.appendChild()')}}{{Spec2('DOM3 Core')}}No change from {{SpecName("DOM2 Core")}}.
{{SpecName('DOM2 Core', 'core.html#ID-184E7107', 'Node.appendChild()')}}{{Spec2('DOM2 Core')}}No change from {{SpecName("DOM1")}}.
{{SpecName('DOM1', 'level-one-core.html#ID-184E7107', 'Node.appendChild()')}}{{Spec2('DOM1')}}Initial definition.
+ +

Browserkompatibilität

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basis Unterstützung{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.0")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basis Unterstützung{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("1.0")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Siehe auch

+ + diff --git a/files/de/web/api/node/childnodes/index.html b/files/de/web/api/node/childnodes/index.html new file mode 100644 index 0000000000..afbddd274e --- /dev/null +++ b/files/de/web/api/node/childnodes/index.html @@ -0,0 +1,70 @@ +--- +title: Node.childNodes +slug: Web/API/Node/childNodes +translation_of: Web/API/Node/childNodes +--- +

{{ ApiRef() }}

+

Allgemein

+

childNodes gibt eine {{ domxref('NodeList') }}, welche alle Kindknoten (childNodes) eines bestimmten HTML-Elements enthält, zurück.

+

Syntax

+
var nodeList = referenzElement.childNodes;
+
+

nodeList ist eine Liste, die alle Kindknoten eines bestimmten Elements der Reihenfolge nach enthält. Falls das Element keine Kindknoten enthält, gibt childNodes eine leere NodeList zurück.
+
+ Diese Eigenschaft kann nur ausgelesen werden (read-only).

+

Beispiel

+

Folgendes HTML-Dokument liegt vor:

+
<!DOCTYPE html>
+<html>
+  <body>
+    <h3>Neue Mitarbeiter eingestellt</h3>
+    <p>Dank der guten Konjunktur letzten Jahres [...]</p>
+  </body>
+</html>
+
+

Nun sollen die childNodes von <body> ausgelesen und in einer Liste namens nodeList gespeichert werden:

+
var bd = document.body;
+
+// Zuerst werden wir überprüfen, ob das <body>-Element überhaupt Kindknoten hat.
+if (bd.hasChildNodes()) {
+   // Nun werden wir die Eigenschaft childNodes auslesen
+   var nodeList = bd.childNodes;
+
+   for(var i = 0; i < nodeList.length; i++) {
+     // So wird nodeList durchlaufen und folgender Code wird an jedem Eintrag ausgeführt
+     // In diesem Fall soll der Name ausgegeben werden
+     alert(nodeList[i].nodeName);
+   }
+}
+
+


+ Diese Liste ist ständig aktuell. Jede Änderung am referenz-Element (hier <body>) bewirkt eine aktualisierung der Liste.
+ Wenn Sie also beispielsweise das erste Element in der Liste löschen, rückt automatisch das zweite Element an Stelle des Ersten.
+ Deshalb lassen sich z.B. auf diese Art alle Kindknoten eines Elements löschen:

+
while(bd.firstChild) {
+    bd.removeChild(bd.firstChild);
+}
+
+

Anmerkungen

+

Mit childNodes erhalten Sie eine Liste aller Kindknoten, einschließlich derer vom Typ {{ domxref("CharacterData") }}. Wenn Sie diese Datenknoten nicht im Index haben wollen, verwenden Sie statt childNodes die Eigenschaft {{ domxref('Element.children') }}.

+

Die Einträge in nodeList sind Objekte, keine Zeichenketten. Für diese Objekte gelten wiederum alle Methoden und Eigenschaften von {{ domxref("Node") }}. Um also Daten aus diesen Objekten auszulesen, müssen deren Eigenschaften ausgelesen werden. Um beispielsweise den Namen eines in nodeList aufgeführten Elements auszulesen, muss man die eigenschaft nodeName auslesen:

+
var name = nodeList[i].nodeName;
+

Das document Objekt hat zwei Kindknoten: Die Doctype-Deklaration und das root-Element, das eine Eigenschaft von {{ domxref("Document") }} ist.
+ Folgendermaßen kann darauf zugegriffen werden:

+
var root = document.documentElement;
+

In (X)HTML-Dokumenten stellt das HTML-Element das root-Element dar.

+

Siehe auch

+ +

Spezifikationen

+ +

{{ languages( { "fr": "fr/DOM/element.childNodes", "ja": "ja/DOM/element.childNodes", "pl": "pl/DOM/element.childNodes", "zh-cn": "cn/DOM/element.childNodes", "de": "de/DOM/element.childNodes" } ) }}

diff --git a/files/de/web/api/node/clonenode/index.html b/files/de/web/api/node/clonenode/index.html new file mode 100644 index 0000000000..d51a489a69 --- /dev/null +++ b/files/de/web/api/node/clonenode/index.html @@ -0,0 +1,135 @@ +--- +title: Node.cloneNode +slug: Web/API/Node/cloneNode +translation_of: Web/API/Node/cloneNode +--- +
{{APIRef("DOM")}}
+ +

Übersicht

+ +

Gibt ein Duplikat des Knotens, auf dem diese Methode aufgerufen wurde, zurück.

+ +

Syntax

+ +
var dupNode = node.cloneNode(deep);
+
+ +
+
node
+
Der Knoten, welcher dupliziert werden soll.
+
dupNode
+
Der duplizierte Knoten.
+
deep
+
true wenn die Kindknoten des Knotens ebenfalls dupliziert werden sollen, false wenn nur der Knoten dupliziert werden soll.
+
+ +
+

Hinweis: In der DOM4 Spezifikation (implementiert in Gecko 13.0 {{geckoRelease(13)}}), ist das Argument deep optional. Es ist dann laut Spezifikation true.

+ +

Leider wurde dies in der letzten Spezifikation geändert, sodass der Standardwert nun false ist. Auch wenn es immer noch optional ist, sollte man das Argument deep aus diesen Kompatibilitätsgründen setzen. Ab Gecko 28.0 {{geckoRelease(28)}} warnt die Konsole den Entwickler, wenn das Argument nicht gesetzt ist.

+
+ +

Beispiel

+ +
    var p = document.getElementById("para1");
+    var p_prime = p.cloneNode(true);
+
+ +

Hinweise

+ +

Der duplizierte Knoten enthält alle Attribute und deren Werte, aber nicht die Eventlistener welche via addEventListener() oder über die jeweilige Elementeigenschaft (z.B. node.onclick = function) gesetzt wurden. Im Fall eines <canvas>-Elements wird das gezeichnete Bild nicht mitkopiert.

+ +

Der mit cloneNode() duplizierte Knoten ist noch nicht Teil des Dokuments und hat keinen Elternknoten bis er mithilfe der Methode {{domxref("Node.appendChild()")}} oder einer anderen vergleichbaren Methode in das Dokument eingefügt wird.

+ +

Wenn deep auf false gesetzt ist, werden die Kindknoten nicht mitkopiert. Dies schließt ebenfalls alle Textelemente mit ein, da diese in einem oder mehreren Kindknoten enthalten sind.

+ +
Warnung: Die Verwendung von cloneNode() kann dazu führen, dass die selbe ID im Dokument mehrmals existiert.
+ +

Wenn der Originalknoten eine ID hat, sollte diese im dupliziertem Knoten geändert oder gelöscht werden, um Probleme zu vermeiden. Dies sollte auch für das name Attribut überlegt werden.

+ +

Um einen Knoten aus einem anderen Dokument zu kopieren sollte die {{domxref("Document.importNode()")}} verwendet werden.

+ +

Browserkompatibilität

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
deep as an optional parameter +

Ja

+ +

(Standard: false)

+
{{CompatGeckoDesktop("13.0")}}{{CompatUnknown}}{{CompatUnknown}} +

Yes

+ +

(default is false)

+
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome für AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
deep as an optional parameter{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile("13.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

Spezifikationen

+ + diff --git a/files/de/web/api/node/firstchild/index.html b/files/de/web/api/node/firstchild/index.html new file mode 100644 index 0000000000..38703904ec --- /dev/null +++ b/files/de/web/api/node/firstchild/index.html @@ -0,0 +1,62 @@ +--- +title: Node.firstChild +slug: Web/API/Node/firstChild +translation_of: Web/API/Node/firstChild +--- +

{{ ApiRef() }}

+ +

Allgemein

+ +

firstChild gibt den ersten Kindknoten (childNode) eines Datenknotens zurück.

+ +

Syntax

+ +
var ersterKindknoten = element.firstChild;
+
+ +

Die Variable ersterKindknoten enthält einen Datenknoten.

+ +

Beispiel

+ +

Folgendes HTML-Dokument ist gegeben:

+ +
<!DOCTYPE html>
+<html>
+  <body>
+    <h3>Texte</h3>
+    <p>Hier steht Text!</p>
+  </body>
+</html>
+
+ +

Um auf das erste Kindelement zuzugreifen, kann man folgenden Code verwenden:

+ +
var ersterKindknoten = document.body.firstChild;
+
+ +

In diesem Fall ist der erste Kindknoten ein Textknoten, da sich zwischen dem Schlusstag des Paragraphs und dem Start-Tag von <body> ein Zeilenumbruch und vier Leerzeichen befinden.

+ +

Anmerkungen

+ + + +

Spezifikationen

+ + + +

Siehe auch:

+ + + +

{{ languages( { "fr": "fr/DOM/element.firstChild", "ja": "ja/DOM/element.firstChild", "pl": "pl/DOM/element.firstChild", "zh-cn": "zh-cn/DOM/Node.firstChild" } ) }}

diff --git a/files/de/web/api/node/haschildnodes/index.html b/files/de/web/api/node/haschildnodes/index.html new file mode 100644 index 0000000000..1ecfb52b48 --- /dev/null +++ b/files/de/web/api/node/haschildnodes/index.html @@ -0,0 +1,120 @@ +--- +title: Node.hasChildNodes() +slug: Web/API/Node/hasChildNodes +tags: + - API DOM Methode Node +translation_of: Web/API/Node/hasChildNodes +--- +
+
{{APIRef("DOM")}}
+
+ +

Die Node.hasChildNodes() Methode liefert einen Boolean Wert der anzeigt ob die aktuelle {{domxref("Node")}} child nodes hat oder nicht.

+ +

Syntax

+ +
result = node.hasChildNodes();
+ +
+
result
+
enthält den return Wert true oder false.
+
+ +

Beispiele

+ +

Das nächste Beispiel entfernt die erste child node innerhalb dem element mit der id "foo" wenn foo child nodes enthält.

+ +
var foo = document.getElementById("foo");
+if (foo.hasChildNodes()) {
+    // do something with 'foo.childNodes'
+}
+
+ +

Polyfill

+ +
;(function(prototype) {
+    prototype.hasChildNodes = prototype.hasChildNodes || function() {
+        return !!this.firstChild;
+    }
+})(Node.prototype);
+
+ +

Zusammenfassung

+ +

Es gibt unterschiedliche Wege herauszufinden ob die node eine child node enthält.

+ + + +

Spezifikation

+ + + +

Browser Kompatibilität

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}7.0{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

 

+ +

Siehe auch

+ + diff --git a/files/de/web/api/node/index.html b/files/de/web/api/node/index.html new file mode 100644 index 0000000000..9f725381a2 --- /dev/null +++ b/files/de/web/api/node/index.html @@ -0,0 +1,365 @@ +--- +title: Node +slug: Web/API/Node +translation_of: Web/API/Node +--- +
{{APIRef("DOM")}}
+ +

A Node is an interface from which a number of DOM types inherit, and allows these various types to be treated (or tested) similarly.

+ +

The following interfaces all inherit from Node its methods and properties: {{domxref("Document")}}, {{domxref("Element")}}, {{domxref("CharacterData")}} (which {{domxref("Text")}}, {{domxref("Comment")}}, and {{domxref("CDATASection")}} inherit), {{domxref("ProcessingInstruction")}}, {{domxref("DocumentFragment")}}, {{domxref("DocumentType")}}, {{domxref("Notation")}}, {{domxref("Entity")}}, {{domxref("EntityReference")}}

+ +

These interfaces may return null in particular cases where the methods and properties are not relevant. They may throw an exception - for example when adding children to a node type for which no children can exist.

+ +

Properties

+ +

Inherits properties from its parents {{domxref("EventTarget")}}.[1]

+ +
+
{{domxref("Node.baseURI")}} {{readonlyInline}}
+
Returns a {{domxref("DOMString")}} representing the base URL. The concept of base URL changes from one language to another; in HTML, it corresponds to the protocol, the domain name and the directory structure, that is all until the last '/'.
+
{{domxref("Node.baseURIObject")}} {{Non-standard_inline()}} {{ Fx_minversion_inline("3") }}
+
(Not available to web content.) The read-only {{ Interface("nsIURI") }} object representing the base URI for the element.
+
{{domxref("Node.childNodes")}} {{readonlyInline}}
+
Returns a live {{domxref("NodeList")}} containing all the children of this node. {{domxref("NodeList")}} being live means that if the children of the Node change, the {{domxref("NodeList")}} object is automatically updated.
+
{{domxref("Node.firstChild")}} {{readonlyInline}}
+
Returns a {{domxref("Node")}} representing the first direct child node of the node, or null if the node has no child.
+
{{domxref("Node.lastChild")}} {{readonlyInline}}
+
Returns a {{domxref("Node")}} representing the last direct child node of the node, or null if the node has no child.
+
{{domxref("Node.localName")}} {{obsolete_inline}}{{readonlyInline}}
+
Returns a {{domxref("DOMString")}} representing the local part of the qualified name of an element. In Firefox 3.5 and earlier, the property upper-cases the local name for HTML elements (but not XHTML elements). In later versions, this does not happen, so the property is in lower case for both HTML and XHTML. {{ gecko_minversion_inline("1.9.2") }}
+ Though recent specifications require localName to be defined on the {{domxref("Element")}} interface, Gecko-based browsers still implement it on the {{domxref("Node")}} interface.
+
{{domxref("Node.namespaceURI")}} {{obsolete_inline}}{{readonlyInline}}
+
The namespace URI of this node, or null if it is no namespace. In Firefox 3.5 and earlier, HTML elements are in no namespace. In later versions, HTML elements are in the http://www.w3.org/1999/xhtml namespace in both HTML and XML trees. {{ gecko_minversion_inline("1.9.2") }}
+ Though recent specifications require namespaceURI to be defined on the {{domxref("Element")}} interface, Gecko-based browsers still implement it on the {{domxref("Node")}} interface.
+
{{domxref("Node.nextSibling")}} {{readonlyInline}}
+
Returns a {{domxref("Node")}} representing the next node in the tree, or null if there isn't such node.
+
{{domxref("Node.nodeName")}} {{readonlyInline}}
+
Returns a {{domxref("DOMString")}} containing the name of the Node. The structure of the name will differ with the name type. E.g. An {{domxref("HTMLElement")}} will contain the name of the corresponding tag, like 'audio' for an {{domxref("HTMLAudioElement")}}, a {{domxref("Text")}} node will have the '#text' string, or a {{domxref("Document")}} node will have the '#document' string.
+
{{domxref("Node.nodePrincipal")}} {{Non-standard_inline()}}{{ Fx_minversion_inline("3") }}
+
A {{ Interface("nsIPrincipal") }} representing the node principal.
+
{{domxref("Node.nodeType")}}{{readonlyInline}}
+
Returns an unsigned short representing the type of the node. Possible values are: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
NameValue
ELEMENT_NODE1
ATTRIBUTE_NODE {{deprecated_inline()}}2
TEXT_NODE3
CDATA_SECTION_NODE {{deprecated_inline()}}4
ENTITY_REFERENCE_NODE {{deprecated_inline()}}5
ENTITY_NODE {{deprecated_inline()}}6
PROCESSING_INSTRUCTION_NODE7
COMMENT_NODE8
DOCUMENT_NODE9
DOCUMENT_TYPE_NODE10
DOCUMENT_FRAGMENT_NODE11
NOTATION_NODE {{deprecated_inline()}}12
+
+
{{domxref("Node.nodeValue")}}
+
Is a {{domxref("DOMString")}} representing the value of an object. For most Node type, this returns null and any set operation is ignored. For nodes of type TEXT_NODE ({{domxref("Text")}} objects), COMMENT_NODE ({{domxref("Comment")}} objects), and PROCESSING_INSTRUCTION_NODE ({{domxref("ProcessingInstruction")}} objects), the value corresponds to the text data contained in the object.
+
{{domxref("Node.ownerDocument")}} {{readonlyInline}}
+
Returns the {{domxref("Document")}} that this node belongs to. If no document is associated with it, returns null.
+
{{domxref("Node.parentNode")}} {{readonlyInline}}
+
Returns a {{domxref("Node")}} that is the parent of this node. If there is no such node, like if this node is the top of the tree or if doesn't participate in a tree, this property returns null.
+
{{domxref("Node.parentElement")}} {{readonlyInline}}
+
Returns an {{domxref("Element")}} that is the parent of this node. If the node has no parent, or if that parent is not an {{domxref("Element")}}, this property returns null.
+
{{domxref("Node.prefix")}} {{obsolete_inline}}{{readonlyInline}}
+
Is a {{domxref("DOMString")}} representing the namespace prefix of the node, or null if no prefix is specified.
+ Though recent specifications require prefix to be defined on the {{domxref("Element")}} interface, Gecko-based browsers still implement it on the {{domxref("Node")}} interface.
+
{{domxref("Node.previousSibling")}} {{readonlyInline}}
+
Returns a {{domxref("Node")}} representing the previous node in the tree, or null if there isn't such node.
+
{{domxref("Node.textContent")}}
+
Is a {{domxref("DOMString")}} representing the textual content of an element and all its descendants.
+
+ +

Methods

+ +

Inherits methods from its parents {{domxref("EventTarget")}}.[1]

+ +
+
{{domxref("Node.appendChild()")}}
+
Insert a {{domxref("Node")}} as the last child node of this element.
+
{{domxref("Node.cloneNode()")}}
+
Clone a {{domxref("Node")}}, and optionally, all of its contents. By default, it clones the content of the node.
+
{{domxref("Node.compareDocumentPosition()")}}
+
 
+
{{domxref("Node.contains()")}}
+
 
+
{{domxref("Node.getFeature()")}} {{obsolete_inline}}
+
...
+
{{domxref("Node.getUserData()")}} {{obsolete_inline}}
+
Allows a user to get some {{domxref("DOMUserData")}} from the node.
+
{{domxref("Node.hasAttributes()")}} {{obsolete_inline}}
+
Returns a {{domxref("Boolean")}} indicating if the element has any attributes, or not.
+
{{domxref("Node.hasChildNodes()")}}
+
Returns a {{domxref("Boolean")}} indicating if the element has any child nodes, or not.
+
{{domxref("Node.insertBefore()")}}
+
Inserts the first {{domxref("Node")}} given in a parameter immediately before the second, child of this element, {{domxref("Node")}}.
+
{{domxref("Node.isDefaultNamespace()")}}
+
 
+
{{domxref("Node.isEqualNode()")}}
+
 
+
{{domxref("Node.isSameNode()")}} {{obsolete_inline}}
+
 
+
{{domxref("Node.isSupported()")}} {{obsolete_inline}}
+
Returns a Boolean flag containing the result of a test whether the DOM implementation implements a specific feature and this feature is supported by the specific node.
+
{{domxref("Node.lookupPrefix()")}}
+
 
+
{{domxref("Node.lookupNamespaceURI()")}}
+
 
+
{{domxref("Node.normalize()")}}
+
Clean up all the text nodes under this element (merge adjacent, remove empty).
+
{{domxref("Node.removeChild()")}}
+
Removes a child node from the current element, which must be a child of the current node.
+
{{domxref("Node.replaceChild()")}}
+
Replaces one child {{domxref("Node")}} of the current one with the second one given in parameter.
+
{{domxref("Node.setUserData()")}} {{obsolete_inline}}
+
Allows a user to attach, or remove, {{domxref("DOMUserData")}} to the node.
+
 
+
+ +

Examples

+ +

Browse all child nodes

+ +

The following function recursively cycles all child nodes of a node and executes a callback function upon them (and upon the parent node itself).

+ +
function DOMComb (oParent, oCallback) {
+  if (oParent.hasChildNodes()) {
+    for (var oNode = oParent.firstChild; oNode; oNode = oNode.nextSibling) {
+      DOMComb(oNode, oCallback);
+    }
+  }
+  oCallback.call(oParent);
+}
+ +

Syntax

+ +
DOMComb(parentNode, callbackFunction);
+ +

Description

+ +

Recursively cycle all child nodes of parentNode and parentNode itself and execute the callbackFunction upon them as this objects.

+ +

Parameters

+ +
+
parentNode
+
The parent node (Node Object).
+
callbackFunction
+
The callback function (Function).
+
+ +

Sample usage

+ +

The following example send to the console.log the text content of the body:

+ +
function printContent () {
+  if (this.nodeValue) { console.log(this.nodeValue); }
+}
+
+onload = function () {
+  DOMComb(document.body, printContent);
+};
+ +

Remove all children nested within a node

+ +
Element.prototype.removeAll = function () {
+  while (this.firstChild) { this.removeChild(this.firstChild); }
+  return this;
+};
+ +

Sample usage

+ +
/* ... an alternative to document.body.innerHTML = "" ... */
+document.body.removeAll();
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG', '#interface-node', 'Node')}}{{Spec2('DOM WHATWG')}}Removed the following properties: attributes, namespaceURI, prefix, and localName.
+ Removed the following methods: isSupported(), hasAttributes(), isSameNode(), getFeature(), setUserData(), and getUserData().
{{SpecName('DOM3 Core', 'core.html#ID-1950641247', 'Node')}}{{Spec2('DOM3 Core')}}The methods insertBefore(), replaceChild(), removeChild(), and appendChild() returns one more kind of error (NOT_SUPPORTED_ERR) if called on a {{domxref("Document")}}.
+ The normalize() method has been modified so that {{domxref("Text")}} node can also be normalized if the proper {{domxref("DOMConfiguration")}} flag is set.
+ Added the following methods: compareDocumentPosition(), isSameNode(), lookupPrefix(), isDefaultNamespace(), lookupNamespaceURI(), isEqualNode(), getFeature(), setUserData(), and getUserData().
+ Added the following properties: baseURI and textContent.
{{SpecName('DOM2 Core', 'core.html#ID-1950641247', 'Node')}}{{Spec2('DOM2 Core')}}The ownerDocument property was slightly modified so that {{domxref("DocumentFragment")}} also returns null.
+ Added the following properties: namespaceURI, prefix, and localName.
+ Added the following methods: normalize(), isSupported() and hasAttributes().
{{SpecName('DOM1', 'level-one-core.html#ID-1950641247', 'Node')}}{{Spec2('DOM1')}}Initial definition.
+ +

 

+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.0")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
getFeature(){{obsolete_inline}}{{CompatNo}}Supported from {{CompatGeckoDesktop("1.0")}} to {{CompatGeckoDesktop("6.0")}}.
+ Removed in {{CompatGeckoDesktop("7.0")}}
{{CompatUnknown}}{{CompatNo}}{{CompatNo}}
getUserData(), setUserData() and hasAttributes() {{deprecated_inline}}{{CompatNo}}Supported from {{CompatGeckoDesktop("1.0")}} to {{CompatGeckoDesktop("21.0")}}.
+ Removed in {{CompatGeckoDesktop("22.0")}}
{{CompatUnknown}}{{CompatNo}}{{CompatNo}}
isSameNode() {{obsolete_inline}}{{CompatNo}}Supported from {{CompatGeckoDesktop("1.0")}} to {{CompatGeckoDesktop("9.0")}}.
+ Removed in {{CompatGeckoDesktop("10.0")}}
{{CompatUnknown}}{{CompatNo}}{{CompatNo}}
isSupported() {{obsolete_inline}}{{CompatUnknown}}Supported from {{CompatGeckoDesktop("1.0")}} to {{CompatGeckoDesktop("21.0")}}.
+ Removed in {{CompatGeckoDesktop("22.0")}}
{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
attributes{{CompatNo}}Supported from {{CompatGeckoDesktop("1.0")}} to {{CompatGeckoDesktop("21.0")}}.
+ Moved to {{domxref("Element")}} in {{CompatGeckoDesktop("22.0")}}
{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatGeckoMobile("1.0")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
getFeature(){{obsolete_inline}}{{CompatNo}}Supported from {{CompatGeckoDesktop("1.0")}} to {{CompatGeckoDesktop("6.0")}}.
+ Removed in {{CompatGeckoDesktop("7.0")}}
{{CompatUnknown}}{{CompatNo}}{{CompatNo}}
+
+ +

[1] Webkit and Blink incorrectly do not make Node inherit from {{domxref("EventTarget")}}.

diff --git a/files/de/web/api/node/innertext/index.html b/files/de/web/api/node/innertext/index.html new file mode 100644 index 0000000000..bd1594471a --- /dev/null +++ b/files/de/web/api/node/innertext/index.html @@ -0,0 +1,90 @@ +--- +title: Node.innerText +slug: Web/API/Node/innerText +tags: + - API DOM Property Reference +translation_of: Web/API/HTMLElement/innerText +--- +
{{APIRef("DOM")}}
+ +

Zusammenfassung

+ +

Node.innerText ist eine Eigenschaft die die "gerenderten" Text Inhalte einer node und ihrer nachfahren representiert. Als getter nähert es sich dem Text an, den ein User erhalten würde wenn sie/er den Inhalt des Elementes mit dem Kursor highlighten und dann zum Clipboard kopieren würde. Dieses Feature wurde ursprünglich von Internet Explorer eingeführt, und wurde förmlich in den HTML standards von 2016 spezifiziert nachdem es von allen Hauptbrowsern übernommen wurde.

+ +

{{domxref("Node.textContent")}} ist eine etwas ähnliche Alternative. Es gibt allerdings wichtige Unterschiede zwischen den beiden.

+ +

Spezifikation

+ + + + + + + + + + + + + + +
SpezifikationStatusKommentar
{{SpecName('HTML WHATWG', 'dom.html#the-innertext-idl-attribute', 'innerText')}}{{Spec2('HTML WHATWG')}} +

Eingeführt, basiert auf dem draft of the innerText specification. Siehe whatwg/html#465 und whatwg/compat#5 für die Historie.

+
+ +

Browser Kompatibilität

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support4{{ CompatGeckoDesktop(45) }}69.6 (probably earlier)3
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support2.3 (probably earlier){{ CompatGeckoMobile(45) }}10 (probably earlier)124.1 (probably earlier)
+
+ +

Siehe auch

+ + diff --git a/files/de/web/api/node/lastchild/index.html b/files/de/web/api/node/lastchild/index.html new file mode 100644 index 0000000000..9b6f98e59e --- /dev/null +++ b/files/de/web/api/node/lastchild/index.html @@ -0,0 +1,41 @@ +--- +title: Node.lastChild +slug: Web/API/Node/lastChild +translation_of: Web/API/Node/lastChild +--- +

{{ ApiRef() }}

+

Allgemein

+

lastChild gibt den letzten Kindknoten (childNode) eines Datenknotens zurück.

+

Syntax

+
var letzterKindknoten = element.lastChild;
+
+

Die Variable letzterKindknoten enthält einen Datenknoten.

+

Beispiel

+

Folgendes HTML-Dokument ist gegeben:

+
<!DOCTYPE html>
+<html>
+  <body>
+    <h3>Texte</h3>
+    <p>Hier steht Text!</p>
+  </body>
+</html>
+
+

Um auf das letzte Kindelement zuzugreifen, kann man folgenden Code verwenden:

+
var letzterKindknoten = document.body.lastChild;
+
+

In diesem Fall ist der letzte Kindknoten ein Textknoten, da sich zwischen dem Schlusstag des Paragraphs und dem Schlusstag des body-Tags ein Zeilenumbruch und zwei Leerzeichen befinden.

+

Anmerkungen

+ +

Spezifikation

+

lastChild (en)

+

Siehe auch:

+ +

{{ languages( { "fr": "fr/DOM/element.lastChild", "ja": "ja/DOM/element.lastChild", "pl": "pl/DOM/element.lastChild" , "zh-cn": "zh-cn/DOM/Node.lastChild" } ) }}

diff --git a/files/de/web/api/node/nextsibling/index.html b/files/de/web/api/node/nextsibling/index.html new file mode 100644 index 0000000000..414e75a8ce --- /dev/null +++ b/files/de/web/api/node/nextsibling/index.html @@ -0,0 +1,60 @@ +--- +title: Node.nextSibling +slug: Web/API/Node/nextSibling +translation_of: Web/API/Node/nextSibling +--- +

{{ ApiRef() }}

+

Allgemein

+

Gibt den Datenknoten zurück, der entsprechend der childNodes-Liste des Elternelements direkt auf den gegebenen Datenknoten folgt. Falls der übergebene Knoten bereits der letzte dieser Liste ist, wird null zurückgegeben.

+

Syntax

+
nextNode = node.nextSibling;
+
+

Beispiele

+

Folgendes HTML-Dokument ist gegeben:

+
<!DOCTYPE html>
+<html>
+  <body>
+    <div>Das ist eine DIV-Box</div>
+    <p>Hier steht Text!</p>
+  </body>
+</html>
+
+

Mit folgendem Code kann der Name des Geschwisterelements der DIV-Box ermittelt werden:

+
// Diese Variable speichert eine Referenz auf das Erste Element, das <body> enthält, also die DIV-Box
+	var element = document.body.children[0];
+
+	// Nun ermitteln wir das folgende Element
+	var folgeElement = element.nextSibling;
+
+	// Ausgabe des nodeNames
+	alert(folgeElement.nodeName);
+
+

Erläuterung:

+

Die Variable element enthält das erste Kindelement des <body>-Tags, also die DIV-Box.
+ folgeElement speichert den ersten Geschwisterknoten der DIV-Box. In diesem Fall ist das ein Textknoten der einen Zeilenvorschub und vier Leerzeichen enthält, die sich in dem HTML-Dokument zwischen dem > der DIV-Box und dem < des <p> befinden. Das alert()-Fenster gibt somit #text aus.

+

Folgendermaßen können alle nachfolgenden Geschwisterknoten ermittelt werden:

+
var element = document.body.children[0];
+var liste = [];
+
+while(element.nextSibling) {
+  var element = liste[liste.push(element.nextSibling)-1];
+}
+
+

Das Skript erzeugt ein Array liste mit folgendem Inhalt:

+
Array[3]
+  0: Text
+  1: HTMLParagraphElement
+  2: Text
+
+

Anmerkungen

+

Am obigen Beispiel lässt sich klar erkennen, dass einige Male ein #text-Knoten im Index auftaucht. Das kommt immer dann vor, wenn sich zwischen den Elementen Whitespace befindet. Da die Eigenschaft nextSibling auch Textknoten berücksichtigt, landet dieser Whitespace letztendlich als Solcher im Index. Falls dies nicht erwünscht ist, sollten Sie statt nextSibling die Eigenschaft {{ domxref("Element.nextElementSibling") }} verwenden

+

Spezifikationen

+ +

{{ languages( { "fr": "fr/DOM/element.nextSibling", "ja": "ja/DOM/element.nextSibling", "pl": "pl/DOM/element.nextSibling" } ) }}

+

Siehe auch

+ diff --git a/files/de/web/api/node/nodevalue/index.html b/files/de/web/api/node/nodevalue/index.html new file mode 100644 index 0000000000..ab9720812e --- /dev/null +++ b/files/de/web/api/node/nodevalue/index.html @@ -0,0 +1,88 @@ +--- +title: Node.nodeValue +slug: Web/API/Node/nodeValue +tags: + - API DOM Gecko Property +translation_of: Web/API/Node/nodeValue +--- +
+
{{APIRef("DOM")}}
+
+ +

Die Node.nodeValue Eigenschaft gibt den Wert der aktuellen Node zurück oder setzt ihn.

+ +

Syntax

+ +
value = node.nodeValue;
+
+ +

value ist ein string der den Inhalt, falls es ihn gibt, der aktuellen node enthält.

+ +

Notizen

+ +

Für das Dokument selbst, gibt nodeValue  null zurück. Für Text, Kommentar, und CDATA nodes, gibt nodeValue den Inhalt der node zurück. Für attribute nodes, wird der Inhalt des Attributes zurückgegeben.

+ +

Die folgende Tabelle zeigt die return Werte der unterschiedlichen Elemente:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Attrvalue of attribute
CDATASectionInhalt der CDATA Section
CommentInhalt des comments
Documentnull
DocumentFragmentnull
DocumentTypenull
Elementnull
NamedNodeMapnull
EntityReferencenull
Notationnull
ProcessingInstructionGesamter Inhalt, ausgenommen des target
TextInhalt der text node
+ +

Wenn nodeValue als null definiert wird, hat das null setzen keine Auswirkung.

+ +

Spezifikation

+ + diff --git a/files/de/web/api/node/normalize/index.html b/files/de/web/api/node/normalize/index.html new file mode 100644 index 0000000000..e49f29e397 --- /dev/null +++ b/files/de/web/api/node/normalize/index.html @@ -0,0 +1,49 @@ +--- +title: Node.normalize() +slug: Web/API/Node/normalize +tags: + - API + - DOM + - Méthode + - Node + - Referenz +translation_of: Web/API/Node/normalize +--- +
+
{{APIRef("DOM")}}
+
+ +

Die Node.normalize() Methode fügt die ausgewählte Node und all Ihre Kindelemente in eine "normalisierte" Form. In einer normalisierten Node sind keine Textnodes leer und es gibt keine parallel existierenden Textnodes.

+ +

Schreibweise

+ +
element.normalize();
+
+ +

Beispiel

+ +
var wrapper = document.createElement("div");
+
+wrapper.appendChild( document.createTextNode("Teil 1 ") );
+wrapper.appendChild( document.createTextNode("Teil 2 ") );
+
+// Her wäre: wrapper.childNodes.length === 2
+// wrapper.childNodes[0].textContent === "Teil 1 "
+// wrapper.childNodes[1].textContent === "Teil 2 "
+
+wrapper.normalize();
+
+// Jetzt: wrapper.childNodes.length === 1
+// wrapper.childNodes[0].textContent === "Teil 1 Teil 2 "
+ +

Spezifikation

+ + + +

Verwandte Themen

+ + diff --git a/files/de/web/api/node/parentnode/index.html b/files/de/web/api/node/parentnode/index.html new file mode 100644 index 0000000000..6481d10a86 --- /dev/null +++ b/files/de/web/api/node/parentnode/index.html @@ -0,0 +1,79 @@ +--- +title: Node.parentNode +slug: Web/API/Node/parentNode +translation_of: Web/API/Node/parentNode +--- +

{{ ApiRef() }}

+

Allgemein

+

Gibt das Elternelement des gegebenen Datenknotens, entsprechend des DOM-Baums zurück.

+

Syntax

+
elternelement = node.parentNode
+
+

elternelement enthält das Elternelement des gegebenen Datenknotens.

+

Beispiel

+
var dokument = document.documentElement.parentNode;
+
+

Anmerkungen

+ +

Siehe auch

+ +

Browserunterstützung

+

{{ CompatibilityTable() }}

+
+ + + + + + + + + + + + + + + + + + + +
FeatureFirefox (Gecko)ChromeInternet ExplorerOperaSafari
Basic support{{ CompatGeckoDesktop(1.0) }}0.2{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{ CompatVersionUnknown() }}{{ CompatGeckoMobile(1) }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+

Spezifikation

+

DOM Level 2 Core: Node.parentNode (en)

+

{{ languages( { "it": "it/DOM/element.parentNode", "ja": "ja/DOM/element.parentNode", "fr": "fr/DOM/element.parentNode", "pl": "pl/DOM/element.parentNode" , "zh-cn": "zh-cn/DOM/Node.parentNode" } ) }}

diff --git a/files/de/web/api/node/previoussibling/index.html b/files/de/web/api/node/previoussibling/index.html new file mode 100644 index 0000000000..0a5bd2f518 --- /dev/null +++ b/files/de/web/api/node/previoussibling/index.html @@ -0,0 +1,69 @@ +--- +title: Node.previousSibling +slug: Web/API/Node/previousSibling +translation_of: Web/API/Node/previousSibling +--- +

{{ ApiRef() }}

+

{{ languages( { "fr": "fr/DOM/element.previousSibling", "ja": "ja/DOM/element.previousSibling", "pl": "pl/DOM/element.previousSibling", "zh-cn": "zh-cn/DOM/Node.previousSibling" } ) }}

+

Allgemein

+

Gibt den Datenknoten zurück, der entsprechend der childNodes-Liste des Elternelements dem gegebenen Datenknoten direkt vorangestellt ist. Falls der übergebene Knoten bereits der erste in dieser Liste ist, wird null zurückgegeben.

+

Syntax

+
vorangestellterKnoten = node.previousSibling;
+
+

Beispiele

+

Folgendes HTML-Dokument ist gegeben:

+
<!DOCTYPE html>
+<html>
+  <body>
+    <div>Das ist eine DIV-Box</div>
+    <p>Hier steht Text!</p>
+    <ul>
+      <li>Punkt 1</li>
+      <li>Punkt 2</li>
+    </ul>
+  </body>
+</html>
+
+

So kann der vorangestellte Datenknoten von <ul> ermittelt werden:

+
	// Diese Variable speichert eine Referenz auf das letzte Element, das <body> enthält, also <ul>
+	var element = document.body.children[2];
+
+	// Nun ermitteln wir durch previousSibling den vorangestellten Knoten
+	var vorangestellterKnoten = element.previousSibling;
+
+	// Ausgabe des Knoten-Namens
+	alert(vorangestellterKnoten.nodeName);
+
+

Erläuterung:

+

Die Variable element enthält das letzte Kindelement des -Tags, also <ul>. vorangestellterKnoten speichert den direkt vorangestellten Geschwisterknoten von <ul>. In diesem Fall ist das ein Textknoten der einen Zeilenvorschub und vier Leerzeichen enthält, die sich in dem HTML-Dokument zwischen dem > von <p> und dem < des <ul> befinden. Das alert()-Fenster gibt somit #text aus.

+

So können alle vorangestellten Datenknoten eines Elements ermittelt werden:

+
var element = document.body.children[2];
+var liste = [];
+
+while(element.previousSibling) {
+  var element = liste[liste.push(element.previousSibling)-1];
+}
+
+

Das Skript erzeugt ein Array liste mit folgendem Inhalt:

+
Array[5]
+  0: Text
+  1: HTMLParagraphElement
+  2: Text
+  3: HTMLDivElement
+  4: Text
+
+

Anmerkungen

+

Um statt dem vorangestellten Datenknoten den Nächsten zu erhalten, verwenden Sie {{ domxref("Node.nextSibling") }}.
+ Da die Eigenschaft previousSibling Textknoten berücksichtigt, kann es sein, dass Sie statt des vorangestellten Elements einen Textknoten als Rückgabewert erhalten. Oft passiert das durch Whitespace aller Art (z.B. Leerzeichen, Zeilenvorschübe), der sich zwischen den beiden Elementen befindet und von previousSibling als Textknoten interpretiert wird.
+ Falls Textknoten nicht berücksichtigt werden sollen, verwenden Sie stattdessen {{ domxref("Element.previousElementSibling") }}

+

Spezifikationen

+ +

Siehe auch

+ diff --git a/files/de/web/api/node/removechild/index.html b/files/de/web/api/node/removechild/index.html new file mode 100644 index 0000000000..86a8dfd460 --- /dev/null +++ b/files/de/web/api/node/removechild/index.html @@ -0,0 +1,82 @@ +--- +title: Node.removeChild() +slug: Web/API/Node/removeChild +tags: + - API + - DOM + - Entfernen + - Knoten + - Löschen + - Methode(2) + - Referenz +translation_of: Web/API/Node/removeChild +--- +
+
{{APIRef("DOM")}}
+
+ +

Die Methode Node.removeChild() entfernt einen Kindknoten aus dem DOM. Gibt den entfernten Knoten zurück.

+ +

Syntax

+ +
var oldChild = element.removeChild(child);
+ODER
+element.removeChild(child);
+
+ + + +

Der entfernte Kindknoten bleibt im Speicher erhalten, ist aber nicht länger Teil des DOM. Mit der ersten Syntax-Form ist es möglich, den entfernten Knoten später im Code wieder zu verwenden, über die oldChild Objektreferenz. In der zweiten Form wird jedoch keine oldChild-Refernenz behalten, also wird (vorausgesetzt dass nirgendwo anders im Code eine Referenz gehalten wird) der Knoten unbenutzbar und nicht erreichbar, und wird nach kurzer Zeit automatisch aus dem Speicher entfernt

+ +

Wenn child kein Kind des Knotens element ist, wirft die Methode eine Exception. Dies passiert auch wenn child zwar zum Aufruf der Methode ein Kind von element war, aber durch einen beim Entfernen des Knotens aufgerufenen Event Handler bereits aus dem DOM entfernt wurde (z.B. blur).

+ +

 

+ +

Beispiele

+ +
<!-- Beispiel HTML -->
+
+<div id="top" align="center">
+  <div id="nested"></div>
+</div>
+
+ +
// Ein bestimmtes Element entfernen, wenn der Elternknoten bekannt ist
+var d = document.getElementById("top");
+var d_nested = document.getElementById("nested");
+var throwawayNode = d.removeChild(d_nested);
+
+ +
// Ein bestimmtes Element entfernen, ohne den Elternknoten zu kennen
+var node = document.getElementById("nested");
+if (node.parentNode) {
+  node.parentNode.removeChild(node);
+}
+
+ +
// Alle Kindknoten eines Elements entfernen
+var element = document.getElementById("top");
+while (element.firstChild) {
+  element.removeChild(element.firstChild);
+}
+
+ +

Spezifikation

+ + + +

Siehe auch

+ + diff --git a/files/de/web/api/node/replacechild/index.html b/files/de/web/api/node/replacechild/index.html new file mode 100644 index 0000000000..09886ba653 --- /dev/null +++ b/files/de/web/api/node/replacechild/index.html @@ -0,0 +1,61 @@ +--- +title: Node.replaceChild +slug: Web/API/Node/replaceChild +translation_of: Web/API/Node/replaceChild +--- +

{{ ApiRef() }}

+ +

Zusammenfassung

+ +

Die Node.replaceChild()-Methode ersetzt den Kind-Knoten (child node) innerhalb des gegebenen Eltern-Knotens (parent node) durch einen anderen.

+ +

Syntax

+ +
replacedNode = parentNode.replaceChild(newChild, oldChild);
+
+ + + +

Beispiel

+ +
// <div>
+//  <span id="childSpan">foo bar</span>
+// </div>
+
+// erzeuge einen leeren Element-Knoten
+// ohne ID, Attribute oder Inhalt
+var sp1 = document.createElement("span");
+
+// setze sein id Attribut auf 'newSpan'
+sp1.setAttribute("id", "newSpan");
+
+// Inhalt für das neue Element erzeugen
+var sp1_content = document.createTextNode("new replacement span element.");
+
+// den erzeugten Inhalt an das Element anhängen
+sp1.appendChild(sp1_content);
+
+// Referenz auf den zu ersetzenden Knoten erzeugen
+var sp2 = document.getElementById("childSpan");
+var parentDiv = sp2.parentNode;
+
+// den existierenden Knoten sp2 mit dem neuen Span-Element sp1 ersetzen
+parentDiv.replaceChild(sp1, sp2);
+
+// Ergebnis:
+// <div>
+//   <span id="newSpan">new replacement span element.</span>
+// </div>
+
+ +

Spezifikation

+ +

DOM Level 1 Core: replaceChild

+ +

DOM Level 2 Core: replaceChild

+ +

{{ languages( { "fr": "fr/DOM/element.replaceChild", "ja": "ja/DOM/element.replaceChild", "pl": "pl/DOM/element.replaceChild", "zh-cn": "zh-cn/DOM/Node.replaceChild" } ) }}

diff --git a/files/de/web/api/node/setuserdata/index.html b/files/de/web/api/node/setuserdata/index.html new file mode 100644 index 0000000000..7c4c714d01 --- /dev/null +++ b/files/de/web/api/node/setuserdata/index.html @@ -0,0 +1,121 @@ +--- +title: Node.setUserData() +slug: Web/API/Node/setUserData +translation_of: Web/API/Node/setUserData +--- +
{{APIRef("DOM")}}{{obsolete_header}}
+ +

Die Methode Node.setUserData()erlaubt es dem Benutzer Daten dem Element hinzuzufügen (oder löschen), ohne dabei die DOM zu modifizieren. Beachte dabei, dass die Daten durch das Nutzen von {{domxref("Node.importNode")}}, {{domxref("Node.cloneNode()")}} und {{domxref("Node.renameNode()")}} nicht mitgegeben werden kann (jedoch kann {{domxref("Node.adoptNode")}} die Information behalten), und bei Vergleichstest mit {{domxref("Node.isEqualNode()")}} werden die Daten nicht berücksichtigt.

+ +

This method offers the convenience of associating data with specific nodes without needing to alter the structure of a document and in a standard fashion, but it also means that extra steps may need to be taken if one wishes to serialize the information or include the information upon clone, import, or rename operations.

+ +
+

The Node.getUserData and {{domxref("Node.setUserData")}} methods are no longer available from Web content. {{domxref("Element.dataset")}} or WeakMap can be used instead.

+
+ +

Syntax

+ +
var prevUserData = someNode.setUserData(userKey, userData, handler);
+ +

Parameters

+ + + +

Beispiel

+ +
var d = document.implementation.createDocument('', 'test', null);
+d.documentElement.setUserData('key', 15, {handle:function (o, k, d, s, ds) {console.log(o+'::'+k+'::'+d+'::'+s+'::'+ds)}}); // 2::key::15::[object Element]::[object Element]
+console.log(d.documentElement.getUserData('key')); // 15
+var e = document.importNode(d.documentElement, true); // causes handler to be called
+console.log(e.getUserData('key')); // null since user data is not copied
+
+ +

Spezifikationen

+ + + + + + + + + + + + + + + + + + + + + +
SpezifikationenStatusKommentar
{{SpecName('DOM WHATWG', '#interface-node', 'Node')}}{{Spec2('DOM WHATWG')}}Removed from the specification.
{{SpecName('DOM3 Core', 'core.html#Node3-setUserData', 'Node.setUserData()')}}{{Spec2('DOM3 Core')}}Initial definition
+ +

Browser Kompabilität

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatNo}}{{CompatGeckoDesktop("1.0")}}
+ {{CompatNo}} {{CompatGeckoDesktop("22.0")}}[1]
{{CompatUnknown}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatNo}}{{CompatGeckoMobile("1.0")}}
+ {{CompatNo}} {{CompatGeckoMobile("22.0")}}[1]
{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}
+
+ +

[1] The method is still available from within chrome scripts.

+ +

Siehe auch

+ + diff --git a/files/de/web/api/node/textcontent/index.html b/files/de/web/api/node/textcontent/index.html new file mode 100644 index 0000000000..c237b6ee70 --- /dev/null +++ b/files/de/web/api/node/textcontent/index.html @@ -0,0 +1,69 @@ +--- +title: Node.textContent +slug: Web/API/Node/textContent +tags: + - API + - DOM + - Eigenschaft + - Kommando API + - NeedsSpecTable + - Referenz +translation_of: Web/API/Node/textContent +--- +
{{APIRef("DOM")}}
+ +

Die Node.textContent Eigenschaft repräsentiert den Text-Inhalt einer Node und ihrer untergeordneten Elemente.

+ +

Syntax

+ +
var text = element.textContent;
+element.textContent = "Dies ist ein Beispiel-Text";
+
+ +

Beschreibung

+ + + +

Unterschiede zu innerText

+ +

Internet Explorer hat element.innerText eingeführt. Die Absicht ist ähnlich, weist aber die folgenden Unterschiede auf:

+ + + +

Unterschiede zu innerHTML

+ +

innerHTML gibt, wie der Name schon sagt, das HTML zurück. Sehr häufig wird dies benutzt, um den Text aus einem Element abzurufen oder ihn zu ändern. Stattdessen sollte lieber textContent verwendet werden. Da der Text nicht als HTML geparst wird, ist es sehr wahrscheinlich, dass die Performance besser ist. Weiterhin umgeht man so auch einen möglichen XSS-Angriffspunkt.

+ +

Beispiel

+ +
// Nehmen wir das folgende HTML Fragment:
+//   <div id="divA">Hier ist <span>etwas</span> Text</div>
+
+// Abrufen des Text-Inhalts:
+var text = document.getElementById("divA").textContent;
+// |text| wird auf "Hier ist etwas Text" gesetzt
+
+// Setzen des Text-Inhalts:
+document.getElementById("divA").textContent = "Hier ist auch Text";
+// Das HTML von divA sieht nun so aus:
+//   <div id="divA">Hier ist auch Text</div>
+
+ +

Browser Kompatibilität

+ +

{{Compat("api.Node.textContent")}}

+ +

Spezifikation

+ + diff --git a/files/de/web/api/notification/index.html b/files/de/web/api/notification/index.html new file mode 100644 index 0000000000..aaf5188c37 --- /dev/null +++ b/files/de/web/api/notification/index.html @@ -0,0 +1,265 @@ +--- +title: Notification +slug: Web/API/notification +translation_of: Web/API/Notification +--- +
{{APIRef("Web Notifications")}} {{ SeeCompatTable() }}
+ +
Das Notification interface wird zum konfigurieren und Anzeigen von desktop notifications verwendet.
+ +

Permissions

+ +

Wenn Sie notifications in einer offenen web app verwenden, fügen sie die desktop-notification permission zu ihrem manifest file hinzu. Notifications können für jedes permission level, hosted oder darüber verwendet werden.

+ +
"permissions": {
+    "desktop-notification":{}
+}
+ +

Konstruktor

+ +
var notification = new Notification(title, options);
+ +

Parameter

+ +
+
title
+
Titel der innerhalb der Notification angezeigt werden muss.
+
options {{optional_inline}}
+
Ein Objekt das optionale Konfigurationsparamter enthält. Es kann die folgenden Einträge enthalten: +
    +
  • dir : Die Ausrichtung des Textes; Verfügbar sind auto, ltr, oder rtl.
  • +
  • lang:  Spezifiziere die verwendete Sprache. Dieser String muss ein valides BCP 47 language tag sein.
  • +
  • body:  Ein String, welcher jeglichen extra Inhalt einer notification beinhaltet.
  • +
  • tag: Die ID einer gegebene notification, um diese abzurufen, zu löschen, zu ersetzen oder zu löschen. 
  • +
  • icon: Die Url für das verwendete Icon in einer notification.
  • +
  • data: Ein Benutzerdefiniertes Datenfeld.
  • +
+
+
+ +

Properties

+ +

Static properties

+ +

Diese Eigenschaften sind nur im Notification-Objekt selbst verfügbar.

+ +
+
{{domxref("Notification.permission")}} {{readonlyinline}}
+
Eine Zeichenkette, die die aktuell gesetzten Berechtigungen Notifications anzuzeigen darstellt. Mögliche Werte sind: denied (der Nutzer erlaubt keine Benachrichtigungen), granted (der Nutzer akzeptiert, dass Benachrichtigungen angezeigt werden) oder default (die Nutzerwahl ist unbekannt, daher verhält sich der Browser wie bei denied).
+
+ +

Instance properties

+ +

Diese Eigenschaften sind nur in Instanzen des Notification-Objekts verfügbar.

+ +
+
{{domxref("Notification.title")}} {{readonlyinline}}
+
Der Titel der Benachrichtigung der in den Parametern des Konstruktors spezifiziert wurde.
+
{{domxref("Notification.dir")}} {{readonlyinline}}
+
Textausrichtung der Benachrichtung welche in den Parametern des Konstruktors spezifiziert wurde.
+
{{domxref("Notification.lang")}} {{readonlyinline}}
+
Sprachcode der Benachrichtung welche in den Parametern des Konstruktors spezifiziert wurde.
+
{{domxref("Notification.body")}} {{readonlyinline}}
+
Textinhalt der Benachrichtung welche in den Parametern des Konstruktors spezifiziert wurde.
+
{{domxref("Notification.tag")}} {{readonlyinline}}
+
ID der Benachrichtung (if any) welche in den Parametern des Konstruktors spezifiziert wurde.
+
{{domxref("Notification.icon")}} {{readonlyinline}}
+
URL des Bildes welches als Icon der Benachrichtgung verwendet wird, wie in den Parametern des Konstruktors spezifiziert wurde
+
{{domxref("Notification.data")}} {{readonlyinline}}
+
Returns a structured clone of the notification’s data.
+
+ +

Event handlers

+ +
+
{{domxref("Notification.onclick")}}
+
A handler for the {{event("click")}} event. It is triggered each time the user clicks on the notification.
+
{{domxref("Notification.onshow")}}
+
A handler for the {{event("show")}} event. It is triggered when the notification is displayed.
+
{{domxref("Notification.onerror")}}
+
A handler for the {{event("error")}} event. It is triggered each time the notification encounters an error.
+
{{domxref("Notification.onclose")}}
+
A handler for the {{event("close")}} event. It is triggered when the user closes the notification.
+
+ +

Methods

+ +

Static methods

+ +

These methods are available only on the Notification object itself.

+ +
+
{{domxref("Notification.requestPermission()")}}
+
Requests permission from the user to display notifications. This method must be called as the result of a user action (for example, an onclick event), and cannot be used without it.
+
+ +

Instance methods

+ +

These properties are available only on an instance of the Notification object or through its prototype. The Notification objects also inherit from the {{domxref("EventTarget")}} interface.

+ +
+
{{domxref("Notification.close()")}}
+
Programmatically closes a notification.
+
+ +

{{page("/en-US/docs/Web/API/EventTarget","Methods")}}

+ +

Example

+ +

Assume this basic HTML:

+ +
<button onclick="notifyMe()">Notify me!</button>
+ +

It's possible to send a notification as follows:

+ +
function notifyMe() {
+  // Let's check if the browser supports notifications
+  if (!("Notification" in window)) {
+    alert("This browser does not support desktop notification");
+  }
+
+  // Let's check whether notification permissions have alredy been granted
+  else if (Notification.permission === "granted") {
+    // If it's okay let's create a notification
+    var notification = new Notification("Hi there!");
+  }
+
+  // Otherwise, we need to ask the user for permission
+  else if (Notification.permission !== 'denied') {
+    Notification.requestPermission(function (permission) {
+      // If the user accepts, let's create a notification
+      if (permission === "granted") {
+        var notification = new Notification("Hi there!");
+      }
+    });
+  }
+
+  // At last, if the user has denied notifications, and you
+  // want to be respectful there is no need to bother them any more.
+}
+ +

See the live result

+ +

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

+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Notifications')}}{{Spec2('Web Notifications')}}Initial specification.
+ +

Browser compatibility

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support5 {{ property_prefix("webkit") }} (see notes)
+ 22
4.0 {{ property_prefix("moz") }} (see notes)
+ 22
{{ CompatNo() }}256 (see notes)
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Mobile
Basic support{{ CompatUnknown() }} +

{{CompatVersionUnknown}}

+
4.0 {{ property_prefix("moz") }} (see notes)
+ 22
1.0.1 {{ property_prefix("moz") }} (see notes)
+ 1.2
{{ CompatNo() }}{{ CompatUnknown() }}{{ CompatNo() }} +

{{CompatVersionUnknown}}

+
+
+ +

Gecko notes

+ + + +

Chrome notes

+ + + +

Android notes

+ + + +

Safari notes

+ + + +

Notes

+ +

{{ref("1")}} Deprecated since Android 4.0.

+ +

See also

+ + diff --git a/files/de/web/api/notification/permission/index.html b/files/de/web/api/notification/permission/index.html new file mode 100644 index 0000000000..bd381fe34c --- /dev/null +++ b/files/de/web/api/notification/permission/index.html @@ -0,0 +1,187 @@ +--- +title: Notification.permission +slug: Web/API/notification/permission +tags: + - API + - DOM + - Notifications + - Property + - Reference +translation_of: Web/API/Notification/permission +--- +

{{APIRef("Web Notifications")}}

+ +

Die schreibgeschützte Berechtigungseigenschaft der Schnittstelle {{domxref ("Notificaton")}} gibt die aktuelle Berechtigung an, die der Benutzer für den aktuellen Ursprung zur Anzeige von Web-Benachrichtigungen erteilt hat.

+ +

{{AvailableInWorkers}}

+ +

Syntax

+ +
var permission = Notification.permission;
+ +

Value

+ +

Ein {{domxref ("DOMString")}} repräsentiert die aktuelle Berechtigung. Der Wert kann sein:

+ + + +

Beispiele

+ +

Das folgende ziemlich ausführliche Snippet könnte verwendet werden, wenn Sie zuerst überprüfen möchten, ob Benachrichtigungen unterstützt werden, und prüfen Sie dann, ob für den aktuellen Ursprung die Erlaubnis für das Senden von Benachrichtigungen gewährt wurde, und fordern Sie dann bei Bedarf eine Genehmigung an, bevor Sie eine Benachrichtigung senden.

+ +
function notifyMe() {
+  // Let's check if the browser supports notifications
+  if (!("Notification" in window)) {
+    console.log("This browser does not support desktop notification");
+  }
+
+  // Let's check whether notification permissions have alredy been granted
+  else if (Notification.permission === "granted") {
+    // If it's okay let's create a notification
+    var notification = new Notification("Hi there!");
+  }
+
+  // Otherwise, we need to ask the user for permission
+  else if (Notification.permission !== 'denied' || Notification.permission === "default") {
+    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.
+}
+ +

Spezifikationen

+ + + + + + + + + + + + + + +
SpezifikationStatusKommentar
{{SpecName("Web Notifications","#dom-notification-permission","permission")}}{{Spec2('Web Notifications')}}Lebensstandard
+ +

Browserkombatibilität

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Grundlegende Unterstützung5 {{ property_prefix("webkit") }} (see notes)
+ 22
{{CompatVersionUnknown}}4.0 {{ property_prefix("moz") }} (see notes)
+ 22
{{ CompatNo() }}256 (see notes)
Vorhanden in den Arbeitskräften{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoDesktop("41.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewEdgeFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
+

Grundlegende Unterstützung

+
{{ CompatUnknown() }} +

{{CompatVersionUnknown}}

+
{{CompatVersionUnknown}}4.0 {{ property_prefix("moz") }} (see notes)
+ 22
1.0.1 {{ property_prefix("moz") }} (see notes)
+ 1.2
{{ CompatNo() }}{{ CompatUnknown() }}{{ CompatNo() }} +

{{CompatVersionUnknown}}

+
Vorhanden in den Arbeitskräften{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile(41.0)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

Firefox OS Notizen

+ +

{{Page("/en-US/docs/Web/API/Notifications_API", "Firefox OS notes")}}

+ +

Chrome Notizen

+ +

{{Page("/en-US/docs/Web/API/Notifications_API", "Chrome notes")}}

+ +

Safari Notizen

+ +

{{Page("/en-US/docs/Web/API/Notifications_API", "Safari notes")}}

+ +

Siehe auch

+ + diff --git a/files/de/web/api/page_visibility_api/index.html b/files/de/web/api/page_visibility_api/index.html new file mode 100644 index 0000000000..c6ad0ac2e4 --- /dev/null +++ b/files/de/web/api/page_visibility_api/index.html @@ -0,0 +1,189 @@ +--- +title: Page Visibility API +slug: Web/API/Page_Visibility_API +translation_of: Web/API/Page_Visibility_API +--- +

{{DefaultAPISidebar("Page Visibility API")}}

+ +

Die Page Visibility API informiert sobald eine Webseite sichtbar ist und sich im Fokus befindet. Mit dem Konzept des "tabbed browsing" ist es recht wahrscheinlich, dass sich jede Webseite irgendwann im Hintergrund befindet und deshalb nicht aktiv sichtbar für den Benutzer ist. Wenn der Benutzer die Webseite minimiert oder in einen anderen Tab wechselt, sendet die API ein {{event("visibilitychange")}} Event über die geänderte Sichtbarkeit der Seite. Anhand des Events können dann spezifische Aktionen ausgeführt oder ein von der Sichtbarkeit abhängiges Verhalten aktiviert werden. Wenn etwa ein Video in der Webseite abgespielt wird, könnte dieses pausieren solange die Seite für den Benutzer unsichtbar ist und automatisch fortsetzen, sobald er zu ihr zurückkehrt. Der Benutzer verliert somit die Stelle in dem Video nicht und kann dieses einfach weiter anschauen.

+ +

Die Status eines {{HTMLElement("iframe")}} sind dieselben wie die des übergeordneten document. Wenn der iframe über CSS Eigenschaften versteckt wird, löst dies nicht die visibility events aus und ändert auch nicht den Status der umliegenden Seite.

+ +

Vorteile

+ +

Die API ist besonders hilfreich, um Ressourcen zu sparen und gibt den Entwicklern die Möglichkeit, nicht benötigte Aufgaben einer Webseite oder Web App zu pausieren solange diese nicht sichtbar ist.

+ +

Use cases

+ +

Einige Beispiele für die Nutzung sind:

+ + + +

Bisher mussten hierfür Workarounds von den Entwicklern implementiert werden. Dafür wurden Lösungen verwendet etwa auf Basis von onblur/onfocus Event-Handlern auf dem window, worüber sich ermitteln lässt ob die Webseite gerade die aktive ist oder nicht. Allerdings teilt dies nicht mit, ob die Webseite gerade für den Benutzer effektiv sichtbar ist oder nicht. Die Page Visibility API addressiert genau das. (Verglichen mit der onblur/onfocus basierten Lösung ist ein zentraler Unterschied, dass dort die Webseite nicht unsichtbar wurde, wenn ein ganz anderes Fenster aktiv wurde oder der Browser selbst den Fokus verloren hat, weil der Benutzer zu einer anderen Applikation gewechselt ist. Eine Webseite wird hier nur unsichtbar, wenn der Benutzer innerhalb des Browserfensters zu einem anderen Tab wechselt oder das Fenster minimiert.)

+ +

Beispiel

+ +

Hier ist ein live Code-Beispiel (eines Videos mit Sound).

+ +

Das Beispiel wurde über folgenden Code realisiert:

+ +
// Set the name of the hidden property and the change event for visibility
+var hidden, visibilityChange;
+if (typeof document.hidden !== "undefined") { // Opera 12.10 and Firefox 18 and later support
+  hidden = "hidden";
+  visibilityChange = "visibilitychange";
+} else if (typeof document.msHidden !== "undefined") {
+  hidden = "msHidden";
+  visibilityChange = "msvisibilitychange";
+} else if (typeof document.webkitHidden !== "undefined") {
+  hidden = "webkitHidden";
+  visibilityChange = "webkitvisibilitychange";
+}
+
+var videoElement = document.getElementById("videoElement");
+
+// If the page is hidden, pause the video;
+// if the page is shown, play the video
+function handleVisibilityChange() {
+  if (document[hidden]) {
+    videoElement.pause();
+  } else {
+    videoElement.play();
+  }
+}
+
+// Warn if the browser doesn't support addEventListener or the Page Visibility API
+if (typeof document.addEventListener === "undefined" || typeof document[hidden] === "undefined") {
+  console.log("This demo requires a browser, such as Google Chrome or Firefox, that supports the Page Visibility API.");
+} else {
+  // Handle page visibility change
+  document.addEventListener(visibilityChange, handleVisibilityChange, false);
+
+  // When the video pauses, set the title.
+  // This shows the paused
+  videoElement.addEventListener("pause", function(){
+    document.title = 'Paused';
+  }, false);
+
+  // When the video plays, set the title.
+  videoElement.addEventListener("play", function(){
+    document.title = 'Playing';
+  }, false);
+
+}
+
+ +

Eigenschaften

+ +

document.hidden Read only

+ +

Liefert true wenn die Webseite als unsichtbar für den Benutzer gewertet wird und false andernfalls.

+ +

document.visibilityState Read only

+ +

Ist ein string welcher den aktuellen Sichtbarkeitsstatus angibt. Mögliche Werte sind:

+ + + +
//startSimulation and pauseSimulation defined elsewhere
+function handleVisibilityChange() {
+  if (document.hidden) {
+    pauseSimulation();
+  } else  {
+    startSimulation();
+  }
+}
+
+document.addEventListener("visibilitychange", handleVisibilityChange, false);
+
+ +

Spezifikationen

+ + + + + + + + + + + + + + + + +
SpezifikationStatusBemerkung
{{SpecName('Page Visibility API')}}{{Spec2('Page Visibility API')}}Initial definition.
+ +

Browserkompatibilität

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support13 {{property_prefix("webkit")}}
+ 33
{{CompatGeckoDesktop(18)}} [2]1012.10[1]7
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support4.4 {{property_prefix("webkit")}}{{CompatGeckoMobile(18)}} [2]1012.10[1]7
+
+ +

[1] Feuert das {{event("visibilitychange")}} Event nicht, wenn das Browserfenster minimiert wird. Ebenso wird hidden nicht auf true gesetzt.

+ +

[2] In den Versionen Firefox 10 bis Firefox 51 einschließlich, konnte diese Eigenschaft verwendet werden mit Vendor-Prefix -moz-.

+ +

Weitere Informationen

+ + diff --git a/files/de/web/api/performance/index.html b/files/de/web/api/performance/index.html new file mode 100644 index 0000000000..14f80850bb --- /dev/null +++ b/files/de/web/api/performance/index.html @@ -0,0 +1,135 @@ +--- +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 provides access to performance-related information for the current page. It's part of the High Resolution Time API, but is enhanced by the Performance Timeline API, the Navigation Timing API, the User Timing API, and the Resource Timing API.

+ +

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. 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}}
+
A {{domxref("PerformanceNavigation")}} object that provides useful context about the operations included in the times listed in timing, including whether the page was a load or a refresh, how many redirections occurred, and so forth. Not available in workers.
+
{{domxref("Performance.timing")}} {{readonlyInline}}
+
A {{domxref("PerformanceTiming")}} object containing latency-related performance information. Not available in workers.
+
{{domxref("Performance.memory", "performance.memory")}} {{Non-standard_inline}}
+
A non-standard extension added in Chrome, this property provides an object with basic memory usage information. You should not use this non-standard API.
+
+ +
+
+

Event handlers

+
+
{{domxref("Performance.onresourcetimingbufferfull")}}
+
An {{domxref("EventTarget")}} which is a callback that will be called when the {{event("resourcetimingbufferfull")}} event is fired.
+
+ +

Methods

+ +

The Performance interface doesn't inherit any methods.

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

Browser compatibility

+ +
+
+ + +

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

+
+
diff --git a/files/de/web/api/performance/now/index.html b/files/de/web/api/performance/now/index.html new file mode 100644 index 0000000000..019bafeb55 --- /dev/null +++ b/files/de/web/api/performance/now/index.html @@ -0,0 +1,164 @@ +--- +title: performance.now() +slug: Web/API/Performance/now +tags: + - API + - Méthode + - Performanz + - Referenz + - Web Performance API +translation_of: Web/API/Performance/now +--- +
{{APIRef("High Resolution Timing")}}
+ +

Die performance.now() Methode gibt einen {{domxref("DOMHighResTimeStamp")}} zurück, der in Millisekunden gemessen wird und auf fünf Tausendstel einer Millisekunde (5 Mikrosekunden) genau ist.

+ +

Der zurückgegebene Wert stellt die Zeit dar, die seit time origin (der {{domxref("PerformanceTiming.navigationStart")}} Eigenschaft und damit der Startzeit) vergangen ist. In einem Web Worker ist die Startzeit die Zeit, in der ihr Ausführungskontext (Thread oder Prozess) erstellt wurde. In einem Browserfenster ist es die Zeit, zu der eine Nutzerin zu dem aktuellen Dokument navigierte (oder die Navigation bestätigte, sollte Bestätigung notwendig gewesen sein). Folgende Punkte sind dabei zu beachten:

+ + + +
t = performance.now();
+ +

Beispiel

+ +
var zeit0 = performance.now();
+machEtwas();
+var zeit1 = performance.now();
+console.log("Der Aufruf von machEtwas dauerte " + (zeit1 - zeit0) + " Millisekunden.");
+
+ +

Anders als andere Zeitmessungsdaten, die in JavaScript verfügbar sind (beispielsweise Date.now), sind die Zeitstempel, die von Performance.now() zurückgegeben werden nicht auf eine Auflösung von einer Millisekunde beschränkt. Stattdessen repräsentieren sie Zeit als Fließkommazahl mit einer Präzision von bis zu einer Mikrosekunde.

+ +

Ebenso anders als Date.now(), wachsen die Werte, die von Performance.now() zurückgegeben werden immer in einem konstanten Tempo, unabhängig von der Systemuhr (die manuell eingestellt oder durch Software wie NTP ungenau geworden sein kann). Ansonsten wird performance.timing.navigationStart + performance.now() annähernd ähnlich zu Date.now() sein.

+ +

Spezifkationen

+ + + + + + + + + + + + + + + + + + + +
SpezifikationStatusKommentar
{{SpecName('Highres Time Level 2', '#dom-performance-now', 'performance.now()')}}{{Spec2('Highres Time Level 2')}}Strengere Definition von Schnittstellen und Typen
{{SpecName('Highres Time', '#dom-performance-now', 'performance.now()')}}{{Spec2('Highres Time')}}Ursprüngliche Definition
+ +

Browserkompatibilität

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Grundsätzliche Unterstützung{{CompatChrome("20.0")}} {{property_prefix("webkit")}}
+ {{CompatChrome("24.0")}} [1]
{{CompatVersionUnknown}}{{CompatGeckoDesktop("15.0")}}10.0{{CompatOpera("15.0")}}{{CompatSafari("8.0")}}
in Web Workern{{CompatChrome("33")}}{{CompatUnknown}}{{CompatGeckoDesktop("34.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
now() in einem dedizierten Worker ist nun unabhängig vom now() des Hauptkontextes.{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoDesktop("45.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
Grundsätzliche Unterstützung{{CompatAndroid("4.0")}}{{CompatChrome("25.0")}}{{CompatVersionUnknown}}{{CompatGeckoMobile("15.0")}}10.0{{CompatNo}}9{{CompatChrome("25.0")}}
in Web Workern{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatGeckoMobile("34.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}
now() in einem dedizierten Worker ist nun unabhängig vom now() des Hauptkontextes.{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile("45.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1] Windows Versionen von Chrome 20 bis 33 geben performance.now() nur mit einer Millisekundengenauigkeit zurück.

+ +

Siehe auch

+ + diff --git a/files/de/web/api/push_api/index.html b/files/de/web/api/push_api/index.html new file mode 100644 index 0000000000..84451b1ac4 --- /dev/null +++ b/files/de/web/api/push_api/index.html @@ -0,0 +1,180 @@ +--- +title: Push API +slug: Web/API/Push_API +translation_of: Web/API/Push_API +--- +
{{SeeCompatTable}}
+ +

Die Push API verleiht Web Applikationen die Fähigkeit, Benachrichtigungen zu empfangen, die von einem Server gesendet werden. Das funktioniert auch, wenn die Web Applikation selbst nicht im Vordergrund oder überhaupt aktuell geladen ist. Dies ermöglicht Entwicklern asynchrone Notizen und Updates an Benutzer zu senden, die sich dafür angemeldet haben. Das Ergebnis ist besseres Engagement mit aktuellem Inhalt.

+ +

Push Konzepte und Anwendung

+ +
+

When implementing PushManager subscriptions, it is vitally important that you protect against CSRF/XSRF issues in your app. See the following articles for more information:

+ + +
+ +

Wenn eine App Push Nachrichten erhalten soll, muss sie ein service worker sein. Wenn der Service Worker aktiv ist, kann er Push Benachrichtigungen abonnieren wie folgt: {{domxref("PushManager.subscribe()")}}.

+ +

Das Resultat {{domxref("PushSubscription")}} enthält sämtliche Information, die die App braucht, um Push Nachrichten zu senden: einen Endpunkt und den Kodierungsschlüssel zum Datenversand.

+ +

Der Service Worker startet bei Bedarf, um eintreffende Nachrichten zu verarbeiten, welche an den Event Handler {{domxref("ServiceWorkerGlobalScope.onpush")}} geliefert werden. Dies erlaubt der App auf einlaufende Push Nachrichten zu reagieren, beispielsweise mit der Darstellung einer Notiz (mit dem Befehl {{domxref("ServiceWorkerRegistration.showNotification()")}}.)

+ +

Jedes Abonnement ist eindeutig für einen Service Worker. Der Endpunkt des Abonnements ist eine eindeutige capability URL: Kenntnis des Endpunkts ist alles was nötig ist, um eine Nachricht an Ihre Applikation zu senden. Die Endpunkt URL ist daher geheim zu halten, da sonst andere Applikationen Nachrichten an Ihre Applikation senden könnten.

+ +

Die Aktivierung einen Service Workers kann eine erhöhte Ressourcennutzung begründen, besonders der Batterie. Die verschiedenen Browser behandeln dies verschieden. Es gibt aktuell keinen Standard dafür. Firefox erlaubt eine begrenzte Anzahlt (quota) Push Nachrichten, die an eine Applikation gesendet werden dürfen, wobei Push Nachrichten, die Notizen generieren, davon ausgenommen sind. Das Limit wird bei jedem Seitenbesuch erneuert. Zum Vergleich verwendet Chrome kein Limit, sondern erfordert, dass jede Push Nachricht mit einer Notiz angezeigt wird.

+ +
+

Note: As of Gecko 44, the allowed quota of push messages per application is not incremented when a new notification fires, when another is still visible, for a period of three seconds. This handles cases where a burst of Push messages is received, and not all generate a visible notification.

+
+ +
+

Note: Chrome versions earlier than 52 require you to set up a project on Google Cloud Messaging to send push messages, and use the associated project number and API key when sending push notifications. It also requires an app manifest, with some special parameters to use this service.

+
+ +

Interfaces

+ +
+
{{domxref("PushEvent")}}
+
Represents a push action, sent to the global scope of a {{domxref("ServiceWorker")}}. It contains information sent from an application to a {{domxref("PushSubscription")}}.
+
{{domxref("PushManager")}}
+
Provides a way to receive notifications from third-party servers, as well as request URLs for push notifications. This interface has replaced the functionality offered by the obsolete {{domxref("PushRegistrationManager")}} interface.
+
{{domxref("PushMessageData")}}
+
Provides access to push data sent by a server, and includes methods to manipulate the received data.
+
{{domxref("PushSubscription")}}
+
Provides a subcription's URL endpoint, and allows unsubscription from a push service.
+
+ +

Service worker additions

+ +

The following additions to the Service Worker API have been specified in the Push API spec to provide an entry point for using Push messages. They also monitor and respond to push and subscription change events.

+ +
+
{{domxref("ServiceWorkerRegistration.pushManager")}} {{readonlyinline}}
+
Returns a reference to the {{domxref("PushManager")}} interface for managing push subscriptions including subscribing, getting an active subscription, and accessing push permission status. This is the entry point into using Push messaging.
+
{{domxref("ServiceWorkerGlobalScope.onpush")}}
+
An event handler fired whenever a {{Event("push")}} event occurs; that is, whenever a server push message is received.
+
{{domxref("ServiceWorkerGlobalScope.onpushsubscriptionchange")}}
+
An event handler fired whenever a {{Event("pushsubscriptionchange")}} event occurs; for example, when a push subscription has been invalidated, or is about to be invalidated (e.g. when a push service sets an expiration time.)
+
+ +

Examples

+ +

Mozilla's ServiceWorker Cookbook contains many useful Push examples.

+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("Push API")}}{{Spec2("Push API")}}Initial definition
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(42.0)}}{{CompatGeckoDesktop(44.0)}}[1][3]{{CompatNo}}[2]{{CompatUnknown}}{{CompatUnknown}}
{{domxref("PushEvent.data")}},
+ {{domxref("PushMessageData")}}
{{CompatNo}}{{CompatGeckoDesktop(44.0)}}[3]{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatNo}}{{CompatGeckoMobile(48.0)}}[4]{{CompatNo}}{{CompatUnknown}}[2]{{CompatUnknown}}{{CompatUnknown}}{{CompatChrome(42.0)}}
{{domxref("PushEvent.data")}},
+ {{domxref("PushMessageData")}}
{{CompatNo}}{{CompatNo}}{{CompatGeckoMobile(48.0)}}[4]{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ + + +

See also

+ + + +
{{DefaultAPISidebar("Push API")}}
diff --git a/files/de/web/api/pushmanager/index.html b/files/de/web/api/pushmanager/index.html new file mode 100644 index 0000000000..96627b0fb0 --- /dev/null +++ b/files/de/web/api/pushmanager/index.html @@ -0,0 +1,161 @@ +--- +title: PushManager +slug: Web/API/PushManager +tags: + - API + - Experimental + - Interface + - NeedsTranslation + - Push + - Push API + - Reference + - Service Workers + - TopicStub + - WebAPI +translation_of: Web/API/PushManager +--- +

{{SeeCompatTable}}{{ApiRef("Push API")}}

+ +

The PushManager interface of the Push API provides a way to receive notifications from third-party servers as well as request URLs for push notifications.

+ +

This interface is accessed via the {{domxref("ServiceWorkerRegistration.pushManager")}} property.

+ +
+

Note: This interface replaces functionality previously offered by the obsolete {{domxref("PushRegistrationManager")}} interface.

+
+ +

Properties

+ +

None.

+ +

Methods

+ +
+
{{domxref("PushManager.getSubscription()")}}
+
Retrieves an existing push subscription. It returns a {{jsxref("Promise")}} that resolves to a {{domxref("PushSubscription")}} object containing details of an existing subscription. If no existing subscription exists, this resolves to a null value.
+
{{domxref("PushManager.permissionState()")}}
+
Returns a {{jsxref("Promise")}} that resolves to the permission state of the current {{domxref("PushManager")}}, which will be one of 'granted', 'denied', or 'prompt'.
+
{{domxref("PushManager.subscribe()")}}
+
Subscribes to a push service. It returns a {{jsxref("Promise")}} that resolves to a {{domxref("PushSubscription")}} object containing details of a push subscription. A new push subscription is created if the current service worker does not have an existing subscription.
+
+ +

Deprecated methods

+ +
+
{{domxref("PushManager.hasPermission()")}} {{deprecated_inline}}
+
Returns a {{jsxref("Promise")}} that resolves to the PushPermissionStatus of the requesting webapp, which will be one of granted, denied, or default. Replaced by {{domxref("PushManager.permissionState()")}}.
+
{{domxref("PushManager.register()")}} {{deprecated_inline}}
+
Subscribes to a push subscription. Replaced by {{domxref("PushManager.subscribe()")}}.
+
{{domxref("PushManager.registrations()")}} {{deprecated_inline}}
+
Retrieves existing push subscriptions. Replaced by {{domxref("PushManager.getSubscription()")}}.
+
{{domxref("PushManager.unregister()")}} {{deprecated_inline}}
+
Unregisters and deletes a specified subscription endpoint. In the updated API, a subscription is unregistered by calling the {{domxref("PushSubscription.unsubscribe()")}} method.
+
+ +

Example

+ +
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);
+      }
+    );
+  });
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Push API','#pushmanager-interface','PushManager')}}{{Spec2('Push API')}}Initial definition.
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(42.0)}}{{CompatGeckoDesktop(44.0)}}{{CompatNo}}{{CompatUnknown}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatChrome(42.0)}}
+
+ +

See also

+ + diff --git a/files/de/web/api/pushmanager/subscribe/index.html b/files/de/web/api/pushmanager/subscribe/index.html new file mode 100644 index 0000000000..5d82a28916 --- /dev/null +++ b/files/de/web/api/pushmanager/subscribe/index.html @@ -0,0 +1,143 @@ +--- +title: PushManager.subscribe() +slug: Web/API/PushManager/subscribe +translation_of: Web/API/PushManager/subscribe +--- +

{{SeeCompatTable}}{{ApiRef("Push API")}}

+ +

Die Methode subscribe() des {{domxref("PushManager")}} Interfaces meldet die API an einem Push-Service an.

+ +

Sie bekommt {{jsxref("Promise")}} als Rückgabewert, welcher sich zu einem {{domxref("PushSubscription")}} Objekt auflösen lässt, und weitere Details der Push-Subscription enthält. Eine neue Push-Subscription wird erstellt falls der aktuelle Service-Worker nicht bereits eine existierende Push-Subscription enthält.

+ +

Syntax

+ +
​PushManager.subscribe(options).then(function(pushSubscription) { ... } );
+ +

Parameter

+ +
+
options {{optional_inline}}
+
Ein Objekt das optionale Konfigurationsparameter enthält. Das Objekt kann die folgenden Eigenschaften (properties) haben: +
    +
  • userVisibleOnly: Ein boolscher Wert der anzeigt, dass die zurückgegebene Push-Subscription nur für Nachrichten genutz wird, dessen Effekt den sie (die Push-Subscription) auslöst, auch nur für den Anwender sichtbar sind.
  • +
+
+
+ +

Returnwert

+ +

{{jsxref("Promise")}} welcher ein {{domxref("PushSubscription")}} Objekt auflöst.

+ +

Beispiel

+ +
this.onpush = function(event) {
+  console.log(event.data);
+  /**********************************************
+  ++ Die Überstzung des Kommentars, folgt noch ++
+  **********************************************/
+  // 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.endpoint);
+        /**********************************************
+        ++ Die Überstzung des Kommentars, folgt noch ++
+        **********************************************/
+        // 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) {
+        /**********************************************
+        ++ Die Überstzung des Kommentars, folgt noch ++
+        **********************************************/
+        // 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);
+      }
+    );
+  });
+ +

Spezifikationen

+ + + + + + + + + + + + + + +
SpezifikationStatusKommentar
{{SpecName('Push API', '#widl-PushManager-subscribe-Promise-PushSubscription--PushSubscriptionOptions-options', 'subscribe()')}}{{Spec2('Push API')}}Initial-Definition.
+ +

Browser-Kompatibilität

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(42.0)}}{{CompatGeckoDesktop(44.0)}}{{CompatNo}}{{CompatUnknown}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatChrome(42.0)}}
+
+ +

Weitere Informationen

+ + diff --git a/files/de/web/api/range/index.html b/files/de/web/api/range/index.html new file mode 100644 index 0000000000..2dd5008afc --- /dev/null +++ b/files/de/web/api/range/index.html @@ -0,0 +1,254 @@ +--- +title: Range +slug: Web/API/Range +tags: + - API + - DOM + - NeedsTranslation + - TopicStub +translation_of: Web/API/Range +--- +

{{ APIRef("DOM") }}

+ +

The Range interface represents a fragment of a document that can contain nodes and parts of text nodes.

+ +

A range can be created using the {{ domxref("Document.createRange", "createRange()") }} method of the {{ domxref("Document") }} object. Range objects can also be retrieved by using the {{ domxref("Selection/getRangeAt", "getRangeAt()") }} method of the {{ domxref("Selection") }} object or the {{domxref("Document/caretRangeFromPoint", "caretRangeAtPoint()")}} method of the {{domxref("Document")}} object.

+ +

There also is the {{domxref("Range.Range()", "Range()")}} constructor available.

+ +

Properties

+ +

There are no inherited properties.

+ +
+
{{domxref("Range.collapsed")}} {{readonlyInline}}
+
Returns a {{domxref("Boolean")}} indicating whether the range's start and end points are at the same position.
+
{{domxref("Range.commonAncestorContainer")}} {{readonlyInline}}
+
Returns the deepest {{ domxref("Node") }} that contains the startContainer and endContainer nodes.
+
{{domxref("Range.endContainer")}} {{readonlyInline}}
+
Returns the {{ domxref("Node") }} within which the Range ends.
+
{{domxref("Range.endOffset")}} {{readonlyInline}}
+
Returns a number representing where in the endContainer the Range ends.
+
{{domxref("Range.startContainer")}} {{readonlyInline}}
+
Returns the {{ domxref("Node") }} within which the Range starts.
+
{{domxref("Range.startOffset")}} {{readonlyInline}}
+
Returns a number representing where in the startContainer the Range starts.
+
+ +

Constructor

+ +
+
{{ domxref("Range.Range()", "Range()") }} {{experimental_inline}}
+
Returns a Range object with the global {{domxref("Document")}} as its start and end.
+
+ +

Methods

+ +

There are no inherited methods.

+ +
+
{{ domxref("Range.setStart()")}}
+
Sets the start position of a Range.
+
{{ domxref("Range.setEnd()")}}
+
Sets the end position of a Range.
+
{{ domxref("Range.setStartBefore()")}}
+
Sets the start position of a Range relative to another {{ domxref("Node") }}.
+
{{ domxref("Range.setStartAfter()")}}
+
Sets the start position of a Range relative to another {{ domxref("Node") }}.
+
{{ domxref("Range.setEndBefore()")}}
+
Sets the end position of a Range relative to another {{ domxref("Node") }}.
+
{{ domxref("Range.setEndAfter()")}}
+
Sets the end position of a Range relative to another {{ domxref("Node") }}.
+
{{ domxref("Range.selectNode()")}}
+
Sets the Range to contain the {{ domxref("Node") }} and its contents.
+
{{ domxref("Range.selectNodeContents()")}}
+
Sets the Range to contain the contents of a {{ domxref("Node") }}.
+
{{ domxref("Range.collapse()")}}
+
Collapses the Range to one of its boundary points.
+
{{ domxref("Range.cloneContents()")}}
+
Returns a {{ domxref("DocumentFragment") }} copying the nodes of a Range.
+
{{ domxref("Range.deleteContents()")}}
+
Removes the contents of a Range from the {{ domxref("Document") }}.
+
{{ domxref("Range.extractContents()")}}
+
Moves contents of a Range from the document tree into a {{ domxref("DocumentFragment") }}.
+
{{ domxref("Range.insertNode()")}}
+
Insert a {{ domxref("Node") }} at the start of a Range.
+
{{ domxref("Range.surroundContents()")}}
+
Moves content of a Range into a new {{ domxref("Node") }}.
+
{{ domxref("Range.compareBoundaryPoints()")}}
+
Compares the boundary points of the Range with another Range.
+
{{ domxref("Range.cloneRange()")}}
+
Returns a Range object with boundary points identical to the cloned Range.
+
{{ domxref("Range.detach()")}}
+
Releases the Range from use to improve performance.
+
{{ domxref("Range.toString()")}}
+
Returns the text of the Range.
+
{{ domxref("Range.compareNode()")}} {{ Obsolete_inline }}{{non-standard_inline}}
+
Returns a constant representing whether the {{domxref("Node")}} is before, after, inside, or surrounding the range.
+
{{ domxref("Range.comparePoint()")}} {{experimental_inline}}
+
Returns -1, 0, or 1 indicating whether the point occurs before, inside, or after the Range.
+
{{ domxref("Range.createContextualFragment()")}}{{experimental_inline}}
+
Returns a {{ domxref("DocumentFragment") }} created from a given string of code.
+
{{ domxref("Range.getBoundingClientRect()") }} {{experimental_inline}}
+
Returns a {{ domxref("DOMRect") }} object which bounds the entire contents of the Range; this would be the union of all the rectangles returned by {{ domxref("range.getClientRects()") }}.
+
{{ domxref("Range.getClientRects()") }} {{experimental_inline}}
+
Returns a list of {{ domxref("DOMRect") }} objects that aggregates the results of {{ domxref("Element.getClientRects()") }} for all the elements in the Range.
+
{{ domxref("Range.intersectsNode()")}} {{experimental_inline}}
+
Returns a boolean indicating whether the given node intersects the Range.
+
{{ domxref("Range.isPointInRange()")}} {{experimental_inline}}
+
Returns a boolean indicating whether the given point is in the Range.
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG', '#interface-range', 'Range')}}{{Spec2('DOM WHATWG')}}Do not use RangeException anymore, use DOMException instead.
+ Made the second parameter of collapse() optional.
+ Added the methods isPointInRange(), comparePoint(), and intersectsNode().
+ Added the constructor Range().
{{SpecName('DOM Parsing', '#extensions-to-the-range-interface', 'Extensions to Range')}}{{Spec2('DOM Parsing')}}Added the method createContextualFragment().
{{SpecName('CSSOM View', '#extensions-to-the-range-interface', 'Extensions to Range')}}{{Spec2('CSSOM View')}}Added the methods getClientRects() and getBoundingClientRect().
{{SpecName('DOM2 Traversal_Range', 'ranges.html#Level-2-Range-Interface', 'Range')}}{{Spec2('DOM2 Traversal_Range')}}Initial specification.
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.0")}} [1]9.09.0{{CompatVersionUnknown}}
Range() constructor {{experimental_inline}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatGeckoDesktop("24.0")}}{{CompatNo}}15.0{{CompatVersionUnknown}}
compareNode() {{obsolete_inline}}{{non-standard_inline()}}{{CompatNo}}{{CompatUnknown}}{{CompatGeckoDesktop("1.0")}}
+ Removed in {{CompatGeckoDesktop("1.9")}}
{{CompatNo}}{{CompatNo}}{{CompatNo}}
isPointInRange(), and comparePoint(){{experimental_inline}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatNo}}15.0{{CompatUnknown}}
intersectsNode() {{experimental_inline}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatGeckoDesktop("17.0")}} [2]{{CompatNo}}15.0{{CompatUnknown}}
getClientRects() and getBoundingClientRect(){{experimental_inline}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoDesktop("2.0")}}915.05
createContextualFragment(){{experimental_inline}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}1115.0{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("1.0")}} [1]9.09.0{{CompatVersionUnknown}}
+
+ +

[1] Starting with Gecko 13.0 {{ geckoRelease("13.0") }} the Range object throws a {{ domxref("DOMException") }} as defined in DOM 4, instead of a RangeException defined in prior specifications.

+ +

[2] Gecko supported it up to Gecko 1.9, then removed it until Gecko 17 where it was reimplemented, matching the spec.

+ +

See also

+ + diff --git a/files/de/web/api/range/range/index.html b/files/de/web/api/range/range/index.html new file mode 100644 index 0000000000..f4dddfe830 --- /dev/null +++ b/files/de/web/api/range/range/index.html @@ -0,0 +1,95 @@ +--- +title: Range() +slug: Web/API/Range/Range +translation_of: Web/API/Range/Range +--- +

{{ APIRef("DOM") }}{{seeCompatTable}}

+ +

Der Range() Konstrukteur gibt ein neu generiertes Objekt wieder, wessen Start und Ende das globale {{domxref("Document")}} Objekt ist.

+ +

Syntax

+ +
range = new Range()
+ +

Beispiele

+ +
range = new Range();
+endNode = document.getElementsByTagName("p").item(3);
+endOffset = document.getElementsByTagName("p").item(3).childNodes.length;
+range.setEnd(endNode,endOffset);
+ +

Spezifikationen

+ + + + + + + + + + + + + + +
SpezifikationStatusKommentar
{{SpecName('DOM WHATWG', '#dom-range', 'Range.Range()')}}{{Spec2('DOM WHATWG')}}Initial definition.
+ +

Browserkompatibilität

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basis Unterstützung{{CompatVersionUnknown}}{{CompatGeckoDesktop("24.0")}}{{CompatNo}}15.0{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basis Unterstützung{{CompatVersionUnknown}}{{CompatGeckoMobile("24.0")}}{{CompatNo}}15.0{{CompatVersionUnknown}}
+
+ +

Siehe auch

+ + + +

 

diff --git a/files/de/web/api/readablestream/index.html b/files/de/web/api/readablestream/index.html new file mode 100644 index 0000000000..43873c162b --- /dev/null +++ b/files/de/web/api/readablestream/index.html @@ -0,0 +1,101 @@ +--- +title: ReadableStream +slug: Web/API/ReadableStream +tags: + - API + - Fetch + - Interface + - Reference + - Streams +translation_of: Web/API/ReadableStream +--- +

{{APIRef("Streams")}}{{SeeCompatTable}}

+ +

Das ReadableStream Interface der Streams API repräsentiert einen lesbaren Datenstrom von Bytes.

+ +

Konstruktor

+ +
+
{{domxref("ReadableStream.ReadableStream", "ReadableStream()")}}
+
Erstellt eine Instanz des ReadableStream Interfaces.
+
+ +

Eigenschaften

+ +
+
{{domxref("ReadableStream.locked")}} {{readonlyInline}}
+
Gibt zurück, ob der Stream bereits für einen Reader gesperrt ist.
+
+ +

Methoden

+ +
+
{{domxref("ReadableStream.cancel()")}}
+
Bricht den Stream ab und signalisiert dadurch, dass der Konsument sein Interesse am Stream verloren hat. Das angegebene reason Argument wird an die darunterliegende Quelle weitergegeben, welche dieses benutzen kann. 
+
{{domxref("ReadableStream.getReader()")}}
+
Erstellt einen Reader, dessen Typ durch die mode Option angegeben wird, und sperrt den Stream für den neuen Reader. Während der Stream gesperrt ist kann kein anderer Reader angelegt werden bis dieser freigegeben wurde.
+
{{domxref("ReadableStream.getIterator()")}}
+
Erstellt einen asyncronen ReadableStream-Iterator und sperrt den Stream für ihn, sodass der Iterator der einzige Leser ist. Während der Stream gesperrt ist kann kein anderer Reader angelegt werden bis dieser freigegeben wurde.
+
{{domxref("ReadableStream.pipeThrough()")}}
+
Bietet die Möglichkeit den Stream mit transformierenden Streams zu verketten.
+
{{domxref("ReadableStream.pipeTo()")}}
+
Pipet den aktuellen ReadableStream zu einem gegebenen {{domxref("WritableStream")}} und gibt ein {{domxref("Promise")}} zurück welches erfüllt ist, wenn der Piping-Prozess erfolgreich beendet wurde oder verwirft es, wenn irgendein anderer Fehler auftritt.
+
{{domxref("ReadableStream.tee()")}}
+
Verzweigt den ReadableStream in zwei neue Stream-Instanzen, auf denen parallel gelesen werden kann.
+
{{domxref("ReadableStream[@@asyncIterator]()")}}
+
Alias der getIterator-Methode.
+
+ +

Benutzung

+ +

Im folgenden Beispiel wird eine {{domxref("Response")}} erzeugt, die HTML-Fragmente einer anderen Ressource fetched und an den Browser streamt.

+ +

Dadurch wird die Benutzung von {{domxref("ReadableStream")}} in Kombination mit {{domxref("Uint8Array")}} gezeigt.

+ +
fetch("https://www.example.org/").then((response) => {
+  const reader = response.body.getReader();
+  const stream = new ReadableStream({
+    start(controller) {
+      // Die folgende Funktion behandelt jeden Daten-Chunk
+      function push() {
+        // "done" ist ein Boolean und "value" ein "Uint8Array"
+        return reader.read().then(({ done, value }) => {
+          // Gibt es weitere Daten zu laden?
+          if (done) {
+            // Teile dem Browser mit, dass wir fertig mit dem Senden von Daten sind
+            controller.close();
+            return;
+          }
+
+          // Bekomme die Daten und sende diese an den Browser durch den Controller weiter
+          controller.enqueue(value);
+        }).then(push);
+      };
+
+      push();
+    }
+  });
+
+  return new Response(stream, { headers: { "Content-Type": "text/html" } });
+});
+ +

Spezifikationen

+ + + + + + + + + + + + + + +
SpezifikationStatusKommentar
{{SpecName('Streams','#rs-class','ReadableStream')}}{{Spec2('Streams')}}Initial definition
+ +

Browserkompatibilität

+ +
{{Compat("api.ReadableStream")}}
diff --git a/files/de/web/api/renderingcontext/index.html b/files/de/web/api/renderingcontext/index.html new file mode 100644 index 0000000000..d290eb830d --- /dev/null +++ b/files/de/web/api/renderingcontext/index.html @@ -0,0 +1,41 @@ +--- +title: RenderingContext +slug: Web/API/RenderingContext +translation_of: Web/API/RenderingContext +--- +

{{APIRef("Canvas API")}}

+ +

RenderingContext ist eine WebIDL-typedef, die auf eine beliebige der Schnittstellen verweisen kann, die einen Grafik-Rendering-Kontext innerhalb eines {{HTMLElement("canvas")}} Elements darstellen: {{domxref("CanvasRenderingContext2D")}}, {{domxref("WebGLRenderingContext")}} oder {{domxref("WebGL2RenderingContext")}}.

+ +

Durch die Verwendung der Kurzform RenderingContext können Methoden und Eigenschaften, die eine beliebige dieser Schnittstellen verwenden können, einfacher spezifiziert und geschrieben werden; da <canvas> mehrere Rendering-Systeme unterstützt, ist es aus Sicht der Spezifikation und der Browser-Implementierung hilfreich, eine Kurzform zu verwenden, die "eine dieser Schnittstellen" bedeutet.

+ +

Als solches ist RenderingContext ein Implementierungsdetail und nicht etwas, das Webentwickler direkt verwenden. Es gibt keine RenderingContext-Schnittstelle, und es gibt keine Objekte, die den Typ RenderingContext implementieren.

+ +

Die primäre Verwendung dieses Typs ist die Definition der {{domxref("HTMLCanvasElement.getContext()")}} Methode des <canvas>-Elements, die einen RenderingContext (d.h. einen beliebigen der Rendering-Kontext Typen) zurückgibt.

+ +

Spezifikationen

+ + + + + + + + + + + + + + +
SpezifikationenStatusKommentar
{{SpecName('HTML WHATWG', "scripting.html#renderingcontext", "RenderingContext")}}{{Spec2('HTML WHATWG')}}Erstdefinition.
+ +

Siehe auch

+ + diff --git a/files/de/web/api/response/index.html b/files/de/web/api/response/index.html new file mode 100644 index 0000000000..ee370f462e --- /dev/null +++ b/files/de/web/api/response/index.html @@ -0,0 +1,120 @@ +--- +title: Response +slug: Web/API/Response +translation_of: Web/API/Response +--- +
{{APIRef("Fetch API")}}
+ +

Die Response Schnittstelle der Fetch API stellt die Antwort auf eine Anfrage dar.

+ +

Sie können ein neues Response-Objekt mithilfe des Konstruktors {{domxref("Response.Response()")}} erstellen. Es ist jedoch wahrscheinlicher, dass Sie ein Response-Objekt als Rückgabewert einer API Operation erhalten, z. B. durch einen Service Worker {{domxref("Fetchevent.respondWith")}} oder ein simples {{domxref("GlobalFetch.fetch()")}}.

+ +

Konstruktor

+ +
+
{{domxref("Response.Response","Response()")}}
+
Erstell ein neues Response Objekt.
+
+ +

Eigenschaften

+ +
+
{{domxref("Response.headers")}} {{readonlyinline}}
+
Enthält das {{domxref("Headers")}} Objekt der Antwort.
+
{{domxref("Response.ok")}} {{readonlyinline}}
+
Enthält einen boolschen Wert, ob die anfrage Erfolgreich war (Status im Bereich von 200-299) oder nicht.
+
{{domxref("Response.redirected")}} {{ReadOnlyInline}}
+
Gibt an, ob die Antwort das Ergebnis einer Weiterleitung ist, d. h. die URL-Liste enthält mehrere Einträge.
+
{{domxref("Response.status")}} {{readonlyinline}}
+
Enthält den Status-Code der Antwort (z. B. 200 bei Erfolg).
+
{{domxref("Response.statusText")}} {{readonlyinline}}
+
Enthält die Statusmeldung, die dem Statuscode entspricht (z. B. OK für 200).
+
{{domxref("Response.type")}} {{readonlyinline}}
+
Enthält den Typ der Antwort (z. B. basic, cors).
+
{{domxref("Response.url")}} {{readonlyinline}}
+
Enthält die URL der Antwort.
+
{{domxref("Response.useFinalURL")}}
+
Enthält einen booleschen Wert, der angibt, ob dies die endgültige URL der Antwort ist.
+
+ +

Response implementiert {{domxref("Body")}}, daher stehen darüber hinaus auch folgende Eigenschaften zur Verfügung:

+ +
+
{{domxref("Body.body")}} {{readonlyInline}}
+
Ein einfacher Getter, der verwendet wird, um einen {{domxref("ReadableStream")}} des Body-Inhalts verfügbar zu machen.
+
{{domxref("Body.bodyUsed")}} {{readonlyInline}}
+
Speichert einen {{domxref("Boolean")}}, der angibt, ob der Body bereits in einer Antwort verwendet wurde.
+
+ +

Methoden

+ +
+
{{domxref("Response.clone()")}}
+
Klont Response Objekt.
+
{{domxref("Response.error()")}}
+
Gibt ein neues Response Objekt zurück, das einem Netzwerkfehler zugeordnet ist.
+
{{domxref("Response.redirect()")}}
+
Erstellt eine neue Antwort mit einer anderen URL.
+
+ +

Response implementiert {{domxref("Body")}}, daher stehen darüber hinaus auch folgende Methoden zur Verfügung:

+ +
+
{{domxref("Body.arrayBuffer()")}}
+
Nimmt einen {{domxref("Response")}} Stream und liest ihn bis zum Ende. Gibt ein Promise zurück, welches in einen {{domxref("ArrayBuffer")}} aufgelöst wird.
+
{{domxref("Body.blob()")}}
+
Nimmt einen {{domxref("Response")}} Stream und liest ihn bis zum Ende. Gibt ein Promise zurück, welches in einen {{domxref("Blob")}} aufgelöst wird.
+
{{domxref("Body.formData()")}}
+
Nimmt einen {{domxref("Response")}} Stream und liest ihn bis zum Ende. Gibt ein Promise zurück, welches in einen {{domxref("FormData")}} Objekt aufgelöst wird.
+
{{domxref("Body.json()")}}
+
Nimmt einen {{domxref("Response")}} Stream und liest ihn bis zum Ende. Gibt ein Promise zurück, welches den Inhalt des Body als {{jsxref("JSON")}} einliest.
+
{{domxref("Body.text()")}}
+
Nimmt einen {{domxref("Response")}} Stream und liest ihn bis zum Ende. Gibt ein Promise zurück, welches in einen {{domxref("USVString")}} (Text) aufgelöst wird.
+
+ +

Beispiele

+ +

In unserem grundlegenden Beispiel zu Fetch (Beispiel live ausführen) verwenden wir einen einfachen Aufruf von fetch(), um ein Bild abzurufen und es in einem {{htmlelement("img")}} Tag anzuzeigen. Der Aufruf von fetch() gibt ein Promise zurück, das zu einem Response Objekt aufgelöst wird, welches mit der Anforderung der Ressource verknüpft ist. Da wir ein Bild anfordern, werden Sie feststellen, dass wir {{domxref("Body.blob")}} ausführen müssen ({{domxref("Response")}} implementiert Body), um der Antwort den richtigen MIME-Type zuzuordnen.

+ +
const image = document.querySelector('.my-image');
+fetch('flowers.jpg').then(function(response) {
+  return response.blob();
+}).then(function(blob) {
+  const objectURL = URL.createObjectURL(blob);
+  image.src = objectURL;
+});
+ +

Sie können auch den {{domxref("Response.Response()")}} Konstruktor verwenden, um Ihr eigenes benutzerdefiniertes Response Objekt zu erstellen:

+ +
const response = new Response();
+ +

Spezifikationen

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Fetch','#response-class','Response')}}{{Spec2('Fetch')}}Initial definition
+ +

Browserkompatibilität

+ + + +

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

+ +

Siehe auch

+ + diff --git a/files/de/web/api/response/response/index.html b/files/de/web/api/response/response/index.html new file mode 100644 index 0000000000..53f3eff566 --- /dev/null +++ b/files/de/web/api/response/response/index.html @@ -0,0 +1,75 @@ +--- +title: Response() +slug: Web/API/Response/Response +translation_of: Web/API/Response/Response +--- +
{{APIRef("Fetch")}}
+ +

Der Response() Konstruktor erstellt ein neues {{domxref("Response")}} Objekt.

+ +

Syntax

+ +
var myResponse = new Response(body, init);
+ +

Parameter

+ +
+
body {{optional_inline}}
+
Ein Objekt, welches den Body für eine Antwort definiert. Das kann entweder null oder eins der folgenden sein: +
    +
  • {{domxref("Blob")}}
  • +
  • {{domxref("BufferSource")}}
  • +
  • {{domxref("FormData")}}
  • +
  • {{domxref("ReadableStream")}}
  • +
  • {{domxref("URLSearchParams")}}
  • +
  • {{domxref("USVString")}}
  • +
+
+
init {{optional_inline}}
+
Ein Objekt mit Optionen, welches benutzerdefinierte Einstellungen enthält, die auf die Antwort angewendet werden sollen. Mögliche Optionen sind: +
    +
  • status: Der Statuscode der Antwort, z. B. 200.
  • +
  • statusText: Die Statusnachricht die dem Statuscode zugeordnet ist, z. B. OK.
  • +
  • headers: Etwaige Header die Sie Ihrer Antwort hinzufügen wollen, die einem {{domxref("Headers")}} Objekt or einem Objekt-Literal von {{domxref("ByteString")}} Schlüsselwertpaaren enthalten sind (siehe HTTP Header für Referenzen).
  • +
+
+
+ +

Beispiel

+ +

In unserem Beispiel für eine Fetch Antwort (live ausführen) erstellen wir ein neues Response Objekt mit dem Konstruktor, dem wir einen neuen {{domxref("Blob")}} als Body und ein init Objekt übergeben, welches einen benutzerdefinierten status und statusText enthält:

+ +
var myBlob = new Blob();
+var init = { "status" : 200 , "statusText" : "SuperSmashingGreat!" };
+var myResponse = new Response(myBlob,init);
+ +

Spezifikationen

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Fetch','#dom-response','Response()')}}{{Spec2('Fetch')}}Initiale Definition
+ +

Browserkompatibilität

+ + + +

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

+ +

Siehe auch

+ + diff --git a/files/de/web/api/rtcicecandidate/index.html b/files/de/web/api/rtcicecandidate/index.html new file mode 100644 index 0000000000..4479c64bb6 --- /dev/null +++ b/files/de/web/api/rtcicecandidate/index.html @@ -0,0 +1,121 @@ +--- +title: RTCIceCandidate +slug: Web/API/RTCIceCandidate +translation_of: Web/API/RTCIceCandidate +--- +

{{APIRef("WebRTC")}}{{SeeCompatTable}}{{draft}}

+ +

Das RTCIceCandidate Interface der WebRTC API repräsentiert einen Kandidaten für einen Internet Connectivity Establishment (ICE) Server, welcher eine {{domxref("RTCPeerConnection")}} herstellt.

+ +

Konstruktoren

+ +
+
{{domxref("RTCIceCandidate.RTCIceCandidate()","RTCIceCandidate()")}}
+
Erstellt ein RTCIceCandidate Objekt.
+
+ +

Properties

+ +
+
{{domxref("RTCIceCandidate.candidate")}} {{readonlyInline}}
+
Ein {{domxref("DOMString")}}, der die Transportadresse für den Kadidaten repräsentiert, welche zur Konnektivitätsprüfung verwendet werden kann. Das Format der Adresse ist ein candidate-attribute, wie in {{RFC(5245)}} definiert. Dieser String ist leer (""), wenn der RTCIceCandidate einen "end of candidates" Indikator repräsentiert.
+
{{domxref("RTCIceCandidate.foundation")}} {{readonlyInline}}
+
Gibt einen eindeutigen Identifikator zurück, der es dem ICE erlaubt, Kandidaten, die in mehreren {{domxref("RTCIceTransport")}} Objekten vorhanden sind, in Beziehung zu setzen.
+
{{domxref("RTCIceCandidate.ip")}} {{readonlyInline}}
+
Gibt die IP-Adresse des Kandidaten zurück.
+
{{domxref("RTCIceCandidate.port")}} {{readonlyInline}}
+
Gibt den Port des Kandidaten zurück.
+
{{domxref("RTCIceCandidate.priority")}} {{readonlyInline}}
+
Gibt die zugewiesene Priorität des Kandidaten zurück.
+
{{domxref("RTCIceCandidate.protocol")}} {{readonlyInline}}
+
Gibt das vom Kandidaten verwendete Protokoll zurück, entweder TCP oder UDP.
+
{{domxref("RTCIceCandidate.relatedAddress")}} {{readonlyInline}}
+
Für einen Kandidaten, welcher von einem anderen abgeleitet ist, wie etwa ein Relay- oder Reflexivkandidat, ist relatedAddress die IP-Adresse des Kandidaten, von dem er abgeleitet ist. Für Hostkandidaten ist sie null.
+
{{domxref("RTCIceCandidate.relatedPort")}} {{readonlyInline}}
+
Für einen Kandidaten, welcher von einem anderen abgeleitet ist, wie etwa ein Relay- oder Reflexivkandidat, ist relatedPort der Port des Kandidaten, von dem er abgeleitet ist. Für Hostkandidaten ist er null.
+
{{domxref("RTCIceCandidate.sdpMid")}} {{readonlyInline}}
+
Enthält, wenn nicht null, den Identifikator der "media stream identification" (wei definiert in RFC 5888) für die Medienkomponente, zu der dieser Kandidat zugeordnet ist.
+
{{domxref("RTCIceCandidate.sdpMLineIndex")}} {{readonlyInline}}
+
Enthält, wenn nicht null, den Index (beginnend bei 0) der Medienbeschreibung (wie definiert in RFC 4566) im SDP, dem dieser Kandidat zugeordnet ist.
+
{{domxref("RTCIceCandidate.tcpType")}} {{readonlyInline}}
+
Wenn protocol den Wert tcp enthält, dann repräsentiert tcpType den Typ des TCP Kandidats. Ansonsten enthält tcpType den Wert null.
+
{{domxref("RTCIceCandidate.type")}} {{readonlyInline}}
+
Einer aus host, srflx, prflx, oder relay.
+
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WebRTC 1.0', '#rtcicecandidate-interface', 'RTCIceCandidate')}}{{Spec2('WebRTC 1.0')}}Initiale definition.
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoDesktop(22)}}   
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewEdgeFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}     {{CompatVersionUnknown}}
+
diff --git a/files/de/web/api/rtcpeerconnection/index.html b/files/de/web/api/rtcpeerconnection/index.html new file mode 100644 index 0000000000..df67ef624c --- /dev/null +++ b/files/de/web/api/rtcpeerconnection/index.html @@ -0,0 +1,379 @@ +--- +title: RTCPeerConnection +slug: Web/API/RTCPeerConnection +translation_of: Web/API/RTCPeerConnection +--- +

{{APIRef}}{{SeeCompatTable}}

+ +

The RTCPeerConnection interface represents a WebRTC connection between the local computer and a remote peer. It is used to handle efficient streaming of data between the two peers.

+ +
+

Note: RTCPeerConnection and {{domxref("RTCSessionDescription")}} are currently prefixed in most browsers, and the {{domxref("navigator.getUserMedia()")}} method is prefixed in many versions of some browsers; you should use code like the following to access these:

+ +
var peerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection ||
+                       window.webkitRTCPeerConnection || window.msRTCPeerConnection;
+var sessionDescription = window.RTCSessionDescription || window.mozRTCSessionDescription ||
+                       window.webkitRTCSessionDescription || window.msRTCSessionDescription;
+
+navigator.getUserMedia = navigator.getUserMedia || navigator.mozGetUserMedia ||
+                       navigator.webkitGetUserMedia || navigator.msGetUserMedia;
+
+ +

Simple code such as this is all it takes to ensure that your project will work on as many versions of as many browsers as possible.

+
+ +

Basic usage

+ +

Basic RTCPeerConnection usage involves negotiating a connection between your local machine and a remote one by generating Session Description Protocol to exchange between the two. The caller starts the process by sending an offer to the remote machine, which responds by either accepting or rejecting the call.

+ +

Both parties (the caller and the called party) need to set up their own RTCPeerConnection instances to represent their end of the peer-to-peer connection:

+ +
var pc = new RTCPeerConnection();
+pc.onaddstream = function(obj) {
+  var vid = document.createElement("video");
+  document.appendChild(vid);
+  vid.srcObject = obj.stream;
+}
+
+// Helper functions
+function endCall() {
+  var videos = document.getElementsByTagName("video");
+  for (var i = 0; i < videos.length; i++) {
+    videos[i].pause();
+  }
+
+  pc.close();
+}
+
+function error(err) {
+  endCall();
+}
+
+ +

Initializing the call

+ +

If you are the one initiating the call, you would use {{domxref("navigator.getUserMedia()")}} to get a video stream, then add the stream to the RTCPeerConnection. Once that's been done, call {{domxref("RTCPeerConnection.createOffer()")}} to create an offer, configure the offer, then send it to the server through which the connection is being mediated.

+ +
// Get a list of friends from a server
+// User selects a friend to start a peer connection with
+navigator.getUserMedia({video: true}, function(stream) {
+  // Adding a local stream won't trigger the onaddstream callback,
+  // so call it manually.
+  pc.onaddstream({stream: stream});
+  pc.addStream(stream);
+
+  pc.createOffer(function(offer) {
+    pc.setLocalDescription(new RTCSessionDescription(offer), function() {
+      // send the offer to a server to be forwarded to the friend you're calling.
+    }, error);
+  }, error);
+});
+
+ +

Answering a call

+ +

On the opposite end, the friend will receive the offer from the server using whatever protocol is being used to do so. Once the offer arrives, {{domxref("navigator.getUserMedia()")}} is once again used to create the stream, which is added to the RTCPeerConnection. An {{domxref("RTCSessionDescription")}} object is created and set up as the remote description by calling {{domxref("RTCPeerConnection.setRemoteDescription()")}}.

+ +

Then an answer is created using {{domxref("RTCPeerConnection.createAnswer()")}} and sent back to the server, which forwards it to the caller.

+ +
var offer = getOfferFromFriend();
+navigator.getUserMedia({video: true}, function(stream) {
+  pc.onaddstream({stream: stream});
+  pc.addStream(stream);
+
+  pc.setRemoteDescription(new RTCSessionDescription(offer), function() {
+    pc.createAnswer(function(answer) {
+      pc.setLocalDescription(new RTCSessionDescription(answer), function() {
+        // send the answer to a server to be forwarded back to the caller (you)
+      }, error);
+    }, error);
+  }, error);
+});
+
+ +

Handling the answer

+ +

Back on the original machine, the response is received. Once that happens, call {{domxref("RTCPeerConnection.setRemoteDescription()")}} to set the response as the remote end of the connection.

+ +
// pc was set up earlier when we made the original offer
+var offer = getResponseFromFriend();
+pc.setRemoteDescription(new RTCSessionDescription(offer), function() { }, error);
+
+ +

Constructor

+ +
+
{{domxref("RTCPeerConnection.RTCPeerConnection", "RTCPeerConnection()")}}
+
Constructor; returns a new RTCPeerConnection object.
+
+ +

Properties

+ +

This interface inherits properties from its parent interface, {{domxref("EventTarget")}}.

+ +
+
{{domxref("RTCPeerConnection.iceConnectionState")}} {{ReadOnlyInline}}
+
Returns an enum of type RTCIceConnectionState that describes the ICE connection state for the connection. When this value changes, a {{event("iceconnectionstatechange")}} event is fired on the object.
+
{{domxref("RTCPeerConnection.iceGatheringState")}} {{ReadOnlyInline}}
+
Returns an enum of type RTCIceGatheringState that describes the ICE gathering state for the connection.
+
{{domxref("RTCPeerConnection.localDescription")}} {{ReadOnlyInline}}
+
Returns a {{domxref("RTCSessionDescription")}} describing the session for the local end of the connection. If it has not yet been set, it can be null.
+
{{domxref("RTCPeerConnection.peerIdentity")}} {{ReadOnlyInline}}
+
Returns a RTCIdentityAssertion, that is a couple of a domain name (idp) and a name (name) representing the identity of the remote peer of this connection, once set and verified. If no peer has yet been set and verified, this property will return null. Once set, via the appropriate method, it can't be changed.
+
{{domxref("RTCPeerConnection.remoteDescription")}} {{ReadOnlyInline}}
+
Returns a {{domxref("RTCSessionDescription")}} describing the session for the remote end of the connection. If it has not yet been set, it can be null.
+
{{domxref("RTCPeerConnection.signalingState")}} {{ReadOnlyInline}}
+
Returns an enum of type RTCSignalingState that describes the signaling state of the local connection. This state describes the SDP offer, that defines the configuration of the connections like the description of the locally associated objects of type {{domxref("MediaStream")}}, the codec/RTP/RTCP options, the candidates gathered by the ICE Agent. When this value changes, a {{event("signalingstatechange")}} event is fired on the object.
+
+ +

Event handlers

+ +
+
{{domxref("RTCPeerConnection.onaddstream")}}
+
Is the event handler called when the {{event("addstream")}} event is received. Such an event is sent when a {{domxref("MediaStream")}} is added to this connection by the remote peer. The event is sent immediately after the call {{domxref("RTCPeerConnection.setRemoteDescription()")}} and doesn't wait for the result of the SDP negotiation.
+
{{domxref("RTCPeerConnection.ondatachannel")}}
+
Is the event handler called when the {{event("datachannel")}} event is received. Such an event is sent when a {{domxref("RTCDataChannel")}} is added to this connection.
+
{{domxref("RTCPeerConnection.onicecandidate")}}
+
Is the event handler called when the {{event("icecandidate")}} event is received. Such an event is sent when a {{domxref("RTCICECandidate")}} object is added to the script.
+
{{domxref("RTCPeerConnection.oniceconnectionstatechange")}}
+
Is the event handler called when the {{event("iceconnectionstatechange")}} event is received. Such an event is sent when the value of {{domxref("RTCPeerConnection.iceConnectionState", "iceConnectionState")}} changes.
+
{{domxref("RTCPeerConnection.onidentityresult")}}
+
Is the event handler called when the {{event("identityresult")}} event is received. Such an event is sent when an identity assertion is generated, via {{domxref("RTCPeerConnection.getIdentityAssertion()", "getIdentityAssertion()")}}, or during the creation of an offer or an answer.
+
{{domxref("RTCPeerConnection.onidpassertionerror")}}
+
Is the event handler called when the {{event("idpassertionerror")}} event is received. Such an event is sent when the associated identity provider (IdP) encounters an error while generating an identity assertion.
+
{{domxref("RTCPeerConnection.onidpvalidationerror")}}
+
Is the event handler alled when the {{event("idpvalidationerror")}} event is received. Such an event is sent when the associated identity provider (IdP) encounters an error while validating an identity assertion.
+
{{domxref("RTCPeerConnection.onnegotiationneeded")}}
+
Is the event handler called when the {{event("negotiationneeded")}} event, sent by the browser to inform that negotiation will be required at some point in the future, is received.
+
{{domxref("RTCPeerConnection.onpeeridentity")}}
+
Is the event handler called when the {{event("peeridentity")}} event, sent when a peer identity has been set and verified on this connection, is received.
+
{{domxref("RTCPeerConnection.onremovestream")}}
+
Is the event handler called when the {{event("removestream")}} event, sent when a {{domxref("MediaStream")}} is removed from this connection, is received.
+
{{domxref("RTCPeerConnection.onsignalingstatechange")}}
+
Is the event handler called when the {{event("signalingstatechange")}} event, sent when the value of {{domxref("RTCPeerConnection.signalingState", "signalingState")}} changes, is received.
+
+ +

Methods

+ +
+
{{domxref("RTCPeerConnection.addIceCandidate()")}}
+
 
+
{{domxref("RTCPeerConnection.addStream()")}}
+
Adds a {{domxref("MediaStream")}} as a local source of audio or video. If the negotiation already happened, a new one will be needed for the remote peer to be able to use it.
+
{{domxref("RTCPeerConnection.close()")}}
+
Abruptly closes a connection.
+
{{domxref("RTCPeerConnection.createAnswer()")}}
+
Creates an answer to the offer received by the remote peer, in a two-part offer/answer negotiation of a connection. The two first parameters are respectively success and error callbacks, the optional third one represent options for the answer to be created.
+
{{domxref("RTCPeerConnection.createDataChannel()")}}
+
Creates a new {{domxref("RTCDataChannel")}} associated with this connection. The method takes a dictionary as parameter, with the configuration required for the underlying data channel, like its reliability.
+
{{domxref("RTCPeerConnection.createDTMFSender()")}}
+
Creates a new {{domxref("RTCDTMFSender")}}, associated to a specific {{domxref("MediaStreamTrack")}}, that will be able to send {{Glossary("DTMF")}} phone signaling over the connection.
+
{{domxref("RTCPeerConnection.createOffer()")}}
+
Creates a request to find a remote peer with a specific configuration. 
+
{{domxref("RTCPeerConnection.generateCertificate()")}}
+
Creates and stores an X.509 certificate and corresponding private key then returns an {{domxref("RTCCertificate")}}, providing access to it.
+
{{domxref("RTCPeerConnection.getConfiguration()")}}
+
 
+
{{domxref("RTCPeerConnection.getIdentityAssertion()")}}
+
Initiates the gathering of an identity assertion. This has an effect only if the {{domxref("RTCPeerConnection.signalingState", "signalingState")}} is not "closed". It is not expected for the application dealing with the RTCPeerConnection: this is automatically done; an explicit call only allows to anticipate the need.
+
{{domxref("RTCPeerConnection.getLocalStreams()")}}
+
Returns an array of {{domxref("MediaStream")}} associated with the local end of the connection. The array may be empty.
+
{{domxref("RTCPeerConnection.getRemoteStreams()")}}
+
Returns an array of {{domxref("MediaStream")}} associated with the remote end of the connection. The array may be empty.
+
{{domxref("RTCPeerConnection.getStats()")}}
+
Creates a new {{domxref("RTCStatsReport")}} that contains and allows access to statistics regarding the connection.
+
{{domxref("RTCPeerConnection.getStreamById()")}}
+
Returns the {{domxref("MediaStream")}} with the given id that is associated with local or remote end of the connection. If no stream matches, it returns null.
+
{{domxref("RTCPeerConnection.removeStream()")}}
+
Removes a {{domxref("MediaStream")}} as a local source of audio or video. If the negotiation already happened, a new one will be needed for the remote peer to stop using it.
+
{{domxref("RTCPeerConnection.setIdentityProvider()")}}
+
Sets the Identity Provider (IdP) to the triplet given in parameter: its name, the protocol used to communicate with it (optional) and an optional username. The IdP will be used only when an assertion will be needed.
+
{{domxref("RTCPeerConnection.setLocalDescription()")}}
+
Changes the local description associated with the connection. The description defines the properties of the connection like its codec. The connection is affected by this change and must be able to support both old and new descriptions. The method takes three parameters, a {{domxref("RTCSessionDescription")}} object to set, and two callbacks, one called if the change of description succeeds, another called if it failed.
+
{{domxref("RTCPeerConnection.setRemoteDescription()")}}
+
Changes the remote description associated with the connection. The description defines the properties of the connection like its codec. The connection is affected by this change and must be able to support both old and new descriptions. The method takes three parameters, a {{domxref("RTCSessionDescription")}} object to set, and two callbacks, one called if the change of description succeeds, another called if it failed.
+
{{domxref("RTCPeerConnection.updateIce()")}}
+
 
+
+ +

Constructor

+ +
new RTCPeerConnection({{domxref("RTCConfiguration")}} configuration, optional {{domxref("MediaConstraints")}} constraints);
+ +
+

Note: While the PeerConnection specification reads like passing an RTCConfiguration object is required, Firefox will supply a default if you don't.

+
+ +

Methods

+ +

createOffer

+ +

void createOffer({{domxref("RTCSessionDescriptionCallback")}} successCallback, {{domxref("RTCPeerConnectionErrorCallback")}} failureCallback, optional {{domxref("MediaConstraints")}} constraints);

+ +

Create offer generates a blob of description data to facilitate a PeerConnection to the local machine. Use this when you've got a remote Peer connection and you want to set up the local one.

+ +

Example

+ +
var pc = new PeerConnection();
+pc.addStream(video);
+pc.createOffer(function(desc){
+  pc.setLocalDescription(desc, function() {
+    // send the offer to a server that can negotiate with a remote client
+  });
+}
+ +

Arguments

+ +
+
successCallback
+
An {{domxref("RTCSessionDescriptionCallback")}} which will be passed a single {{domxref("RTCSessionDescription")}} object
+
errorCallback
+
An {{domxref("RTCPeerConnectionErrorCallback")}} which will be passed a single {{domxref("DOMError")}} object
+
[optional] constraints
+
An optional {{domxref("MediaConstraints")}} object.
+
+ +

createAnswer

+ +

void createAnswer({{domxref("RTCSessionDescriptionCallback")}} successCallback, {{domxref("RTCPeerConnectionErrorCallback")}} failureCallback, optional {{domxref("MediaConstraints")}} constraints)")

+ +

Respond to an offer sent from a remote connection.

+ +

Example

+ +
var pc = new PeerConnection();
+pc.setRemoteDescription(new RTCSessionDescription(offer), function() {
+  pc.createAnswer(function(answer) {
+    pc.setLocalDescription(answer, function() {
+      // send the answer to the remote connection
+    })
+  })
+});
+ +

Arguments

+ +
+
successCallback
+
An {{domxref("RTCSessionDescriptionCallback")}} which will be passed a single {{domxref("RTCSessionDescription")}} object
+
errorCallback
+
An {{domxref("RTCPeerConnectionErrorCallback")}} which will be passed a single {{domxref("DOMError")}} object
+
[optional] constraints
+
An optional {{domxref("MediaConstraints")}} object.
+
+ +

updateIce()

+ +

updateIce(optional {{domxref("RTCConfiguration")}} configuration, optional {{domxref("MediaConstraints")}} constraints)

+ +

The updateIce method updates the ICE Agent process of gathering local candidates and pinging remote candidates. If there is a mandatory constraint called "IceTransports" it will control how the ICE engine can act. This can be used to limit the use to TURN candidates by a callee to avoid leaking location information prior to the call being accepted. This call may result in a change to the state of the ICE Agent, and may result in a change to media state if it results in connectivity being established.

+ +

Example

+ +
 
+ +

addIceCandidate()

+ +

addIceCandidate ({{domxref("RTCIceCandidate")}} candidate, {{domxref("Function")}} successCallback, {{domxref("RTCPeerConnectionErrorCallback")}} failureCallback);

+ +

The addIceCandidate() method provides a remote candidate to the ICE Agent. In addition to being added to the remote description, connectivity checks will be sent to the new candidates as long as the "IceTransports" constraint is not set to "none". This call will result in a change to the connection state of the ICE Agent, and may result in a change to media state if it results in different connectivity being established.

+ +

Example

+ +
  pc.addIceCandidate(new RTCIceCandidate(candidate));
+
+ +

createDataChannel

+ +

{{domxref("RTCDataChannel")}} createDataChannel ({{domxref("DOMString")}} label, optional {{domxref("RTCDataChannelInit")}} dataChannelDict);

+ +

Creates a data channel for sending non video or audio data across the peer connection

+ +

Example

+ +
var pc = new PeerConnection();
+var channel = pc.createDataChannel("Mydata");
+channel.onopen = function(event) {
+  channel.send('sending a message');
+}
+channel.onmessage = function(event) { console.log(event.data); }
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WebRTC 1.0')}}{{Spec2('WebRTC 1.0')}}Initial definition.
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatVersionUnknown}}    
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatVersionUnknown}}     {{CompatVersionUnknown}}
+
+ +

See also

+ + diff --git a/files/de/web/api/rtcrtptransceiver/direction/index.html b/files/de/web/api/rtcrtptransceiver/direction/index.html new file mode 100644 index 0000000000..644e007d52 --- /dev/null +++ b/files/de/web/api/rtcrtptransceiver/direction/index.html @@ -0,0 +1,82 @@ +--- +title: RTCRtpTransceiver.direction +slug: Web/API/RTCRtpTransceiver/direction +tags: + - API + - Attribut + - RTCRtpTransceiver + - RTP + - Richtung + - Transceiver + - Transceiver Richtung + - WebRTC + - direction +translation_of: Web/API/RTCRtpTransceiver/direction +--- +
{{APIRef("WebRTC")}}
+ +

Das {{domxref("RTCRtpTransceiver")}} direction Attribut gibt als String die bevorzugte Transceiver-Richtung an. Es muss sich hierbei um einen Wert des {{domxref("RTCRtpTransceiverDirection")}} Enum handeln.

+ +

Die tatsächliche, aktuelle Richtung des Transceivers kann über das {{domxref("RTCRtpTransceiver.currentDirection", "currentDirection")}} Attribut abgelesen werden.

+ +

Syntax

+ +
var direction = RTCRtpTransceiver.direction
+ +

Value

+ +

Ein {{domxref("DOMString")}}, dessen Wert einem Wert des RTCRtpTransceiverDirection Enum / Aufzählungstypen entspricht und die bevorzugte Transceiver-Richtung angibt. {{page("/en-US/docs/Web/API/RTCRtpTransceiverDirection", "Values")}}

+ +

Exceptions

+ +

Wird der direction Wert eines Transceivers gesetzt, können folgende Fehler auftreten:

+ +
+
InvalidStateError
+
Der Receiver des Transceivers {{domxref("RTCPeerConnection")}} wurde bereits geschlossen und befindet sich nun im closed Zustand oder der {{domxref("RTCRtpReceiver")}} wurde gestoppt und befinet sich im stopped Zustand.
+
+ +

Hinweise zur Nutzung

+ +

Ändern der Übertragungsrichtung

+ +

Wird der Wert des direction Attributes geändert, wird eine InvalidStateError Ausnahme geworfen, insofern die RTCPeerConnection bereits geschlossen wurde oder aber der jeweils betroffene Receiver oder Sender bereits gestoppt wurde.

+ +

Wenn der neu gesetzte Wert für direction sich vom aktuellen Wert unterscheidet, muss die Übertragung mit dem Peer neu verhandelt werden, es wird also ein {{event("negotiationneeded")}} Event auf der {{domxref("RTCPeerConnection")}} ausgelöst.

+ +

Transceiver-Richtung in SDP

+ +

Der direction Wert wird von {{domxref("RTCPeerConnection.createOffer()")}} bzw. {{domxref("RTCPeerConnection.createAnswer()")}} genutzt, um die entsprechenden SDP-Nachrichten zu generieren. SDP stellt die Richtung über eine Attribut-Zeile (a-line) dar. Wenn die Richtung des Transceivers als "sendrecv" definiert wurde, so enthält die hierzu erzeugte SDP-Nachricht folgende Attribut-Zeile:

+ +
a=sendrecv
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("WebRTC 1.0", "#dom-rtcrtptransceiver-direction", "RTCRtpTransceiver.direction")}}{{Spec2("WebRTC 1.0")}}
+ +

Browser compatibility

+ +
+ + +

{{Compat("api.RTCRtpTransceiver.direction")}}

+
+ +

See also

+ + diff --git a/files/de/web/api/rtcrtptransceiver/index.html b/files/de/web/api/rtcrtptransceiver/index.html new file mode 100644 index 0000000000..0bf844cf0f --- /dev/null +++ b/files/de/web/api/rtcrtptransceiver/index.html @@ -0,0 +1,85 @@ +--- +title: RTCRtpTransceiver +slug: Web/API/RTCRtpTransceiver +tags: + - API + - Interface + - Media + - MediaStreamTrack + - NeedsTranslation + - RTCRtpTransceiver + - RTP + - Reference + - SDP + - TopicStub + - Transceiver + - WebRTC +translation_of: Web/API/RTCRtpTransceiver +--- +
{{APIRef("WebRTC")}}
+ +

The WebRTC interface RTCRtpTransceiver describes a permanent pairing of an {{domxref("RTCRtpSender")}} and an {{domxref("RTCRtpReceiver")}}, along with some shared state.

+ +

Each {{Glossary("SDP")}} media section describes one bidirectional SRTP ("Secure Real Time Protocol") stream (excepting the media section for {{domxref("RTCDataChannel")}}, if present). This pairing of send and receive SRTP streams is significant for some applications, so RTCRtpTransceiver is used to represent this pairing, along with other important state from the media section. Each non-disabled SRTP media section is always represented by exactly one transceiver.

+ +

A transceiver is uniquely identified using its {{domxref("RTCRtpTransceiver.mid", "mid")}} property, which is the same as the media ID (mid) of its corresponding m-line. An RTCRtpTransceiver is associated with an m-line if its mid is non-null; otherwise it's considered disassociated.

+ +

Properties

+ +
+
{{domxref("RTCRtpTransceiver.currentDirection", "currentDirection")}} {{ReadOnlyInline}}
+
A string from the enum {{domxref("RTCRtpTransceiverDirection")}} which indicates the transceiver's current directionality, or null if the transceiver is stopped or has never participated in an exchange of offers and answers.
+
{{domxref("RTCRtpTransceiver.direction", "direction")}}
+
A string from the enum {{domxref("RTCRtpTransceiverDirection")}} which is used to set the transceiver's desired direction.
+
{{domxref("RTCRtpTransceiver.mid", "mid")}} {{ReadOnlyInline}}
+
The media ID of the m-line associated with this transceiver. This association is established, when possible, whenever either a local or remote description is applied. This field is null if neither a local or remote description has been applied, or if its associated m-line is rejected by either a remote offer or any answer.
+
{{domxref("RTCRtpTransceiver.receiver", "receiver")}} {{ReadOnlyInline}}
+
The {{domxref("RTCRtpReceiver")}} object that handles receiving and decoding incoming media.
+
{{domxref("RTCRtpTransceiver.sender", "sender")}} {{ReadOnlyInline}}
+
The {{domxref("RTCRtpSender")}} object responsible for encoding and sending data to the remote peer.
+
{{domxref("RTCRtpTransceiver.stopped", "stopped")}}
+
Indicates whether or not sending and receiving using the paired RTCRtpSender and RTCRtpReceiver has been permanently disabled, either due to SDP offer/answer, or due to a call to {{domxref("RTCRtpTransceiver.stop", "stop()")}}.
+
+ +

Methods

+ +
+
{{domxref("RTCRtpTransceiver.setCodecPreferences", "setCodecPreferences()")}}
+
A list of {{domxref("RTCRtpCodecParameters")}} objects which override the default preferences used by the {{Glossary("user agent")}} for the transceiver's codecs.
+
{{domxref("RTCRtpTransceiver.stop", "stop()")}}
+
Permanently stops the RTCRtpTransceiver. The associated sender stops sending data, and the associated receiver likewise stops receiving and decoding incoming data.
+
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("WebRTC 1.0", "#rtcrtptransceiver-interface", "RTCRtpTransceiver")}}{{Spec2("WebRTC 1.0")}}
+ +

Browser compatibility

+ +
+ + +

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

+
+ +

See also

+ + diff --git a/files/de/web/api/service_worker_api/index.html b/files/de/web/api/service_worker_api/index.html new file mode 100644 index 0000000000..54e3e1d86e --- /dev/null +++ b/files/de/web/api/service_worker_api/index.html @@ -0,0 +1,280 @@ +--- +title: Service Worker API +slug: Web/API/Service_Worker_API +tags: + - API + - Offline + - Referenz + - Service-Worker + - Worker +translation_of: Web/API/Service_Worker_API +--- +
+

{{ServiceWorkerSidebar}}

+ +

{{ SeeCompatTable() }}

+ +

Service-Worker verhalten sich im Wesentlichen wie Proxy-Server, welche zwischen der Webanwendung bzw. dem Browser und dem Netzwerk (sofern dieses verfügbar ist) sitzen. Sie sollen u. a. das Erstellen wirksamer Offline-Erfahrungen ermöglichen und können Netzwerkanfragen abfangen und passende Maßnahmen abhängig davon ergreifen, ob das Netzwerk verfügbar ist und ob der Server veränderte Ressourcen enthält. Sie erlauben außerdem den Zugriff auf Push-Benachrichtigungen und Background Sync APIs.

+
+ +

Konzepte von Service-Workern und deren Nutzung

+ +

Ein Service-Worker ist ein ereignisgesteuerter Worker, der an einem Ursprung und einem Pfad registriert ist. Sie ist eine JavaScript-Datei, die in Abhängigkeit zu einer Webseite steht, Anfragen von Ressourcen abfängt und cached. In manchen Situationen kann es das Verhalten der Webseite beeinflussen. Ein häufiger Anwendungsfall ist die Abfrage, ob ein Netzwerk verfügbar ist, oder nicht.

+ +

Ein Service-Worker läuft in einem Worker-Kontext. Es hat keinerlei Zugriff auf das DOM und läuft in einem separaten Thread, also isoliert vom JavaScript, dass die Hauptinteraktionslogik der Website steuert. Es läuft vollständig asynchron und verhindert die Ausführung anderer Scripte nicht. Daraus resultiert, dass APIs wie XHR  oder LocalStorage nicht in Service-Workern benutzt werden können.

+ +

Service-Worker laufen aus Sicherheitsgründen nur über das HTTPS-Protokoll. Veränderte Netzwerkanfragen könnten "Man in the middle"-Angriffe deutlich leichter machen.

+ +
+

Hinweis: Service-Worker haben in Bereichen wie AppCache gezeigt, dass sie dort besonders gut genutzt werden können, da sie keine Vermutungen darüber treffen, was Sie machen wollen und brechen ihre Aktionen entsprechend ab. Sie haben deshalb die Kontrolle über alles.

+
+ +
+

Hinweis: Service-Worker basieren auf Promises. Generell sind sie abhängig von Anfragen und sie werden mit einer erfolgreichen oder einer fehlerhaften Aktion antworten. Die Architektur ist deshalb ideal dafür.

+
+ +

Registrierung

+ +

Ein Service-Worker wird über die {{domxref("ServiceWorkerContainer.register()")}}-Methode registriert. Falls sie erfolgreich war, wird Ihr Service-Worker vom Client heruntergeladen und versucht eine Installation/Aktivierung (siehe unten)  für URLs, die innerhalb der Quelle liegen oder die URLs, die Sie vorgeben.

+ +

Download, Installation und Aktivierung

+ +

Ihr Service-Worker muss folgenden Lebenszyklus durchlaufen:

+ +
    +
  1. Download
  2. +
  3. Installation
  4. +
  5. Aktivierung
  6. +
+ +

Der Service-Worker wird sofort mit heruntergeladen, sobald der Nutzer erstmals eine von Service-Workern kontrollierte Seite aufruft.

+ +

Danach wird es alle 24 Stunden neu heruntergeladen. Es kann auch in kürzeren Abständen heruntergeladen werden, aber die 24 Stunden können nicht überschritten werden. Damit sollen die Ladezeiten kürzer werden.

+ +

Eine Installation wird versucht, wenn die heruntergeladene Datei neu ist, also Unterschiede byteweise verglichen mit dem bestehenden Service-Worker aufweist oder es der erste Service-Worker ist, der für diese Seite heruntergeladen wurde.

+ +

Wenn ein Service-Worker erstmals verfügbar ist, wird eine Installation versucht. Nach einer erfolgreichen Installation ist es aktiviert.

+ +

Wenn bereits ein bestehender Service-Worker installiert wurde, wird die neue Version im Hintergrund installiert, aber noch nicht aktiviert. Zu diesen Zeitpunkt wartet der Worker, bis alle Seiten heruntergeladen wurden, die noch den alten Service-Worker nutzen. Sobald alle Seiten geladen worden sind, wird der neue Service-Worker aktiviert.

+ +

Sie können ein Ereignishandler für das {{domxref("InstallEvent")}} erstellen. Standardmäßig wird der Worker für den Einsatz vorbereitet, wenn das Event feuert. Zum Beispiel beim erstellen eines Caches, bei der die Built-In Storage API verwendet wird und Assets hineingeladen werden, damit die App offline verwendet werden kann.

+ +

Außerdem existiert ein activate-Event. Wenn es feuert, ist es ein guter Zeitpunkt die alten Caches und andere Daten zu bereinigen, die mit der vorherigen Version ihres Workers zusammenhängen.

+ +

Ihr Service-Worker kann mit dem {{domxref("FetchEvent")}} auf Anfragen antworten. Sie können die Antworten auf die Anfragen verändern, wie Sie wollen. Nutzen Sie dazu die {{domxref("FetchEvent.respondWith") }}-Methode.

+ +
+

Hinweis: Weil oninstall/onactivate eine Weile benötigen, um ihre Aktionen abzuschließen, ist es empfehlenswert, eine waitUntil-Methode bereitzustellen, die, wenn oninstall oder onactivate gefeuert werden, ein Promise geliefert wird. Events, die der Funktion dienen, werden dem Service-Worker nicht enthalten und der Promise wird erfolgreich ausgeführt.

+
+ +

Für eine komplette Anleitung, die zeigt, wie Sie Ihr erstes Beispiel erstellen, siehe Using Service Workers.

+ +

Weitere Anwendungsbereiche

+ +

Service-Worker werden auch benutzt für:

+ + + +

In Zukunft werden Service-Worker zu weiteren nützlichen Dingen fähig sein, die sie näher an eine native App bringen. Andere Spezifikationen können und werden den Service-Worker-Kontext benutzen. Zum Beispiel:

+ + + +

Schnittstellen

+ +
+
{{domxref("Cache") }}
+
Repräsentiert einen Speicher für {{domxref("Request")}} / {{domxref("Response")}}-Objeltpaare, die als ein Teil des {{domxref("ServiceWorker")}}-Lifecycles agieren.
+
{{domxref("CacheStorage") }}
+
Repräsentiert einen Speicher für {{domxref("Cache")}}-Objekte. Es ist das Hauptverzeichnis für {{domxref("ServiceWorker")}}. Es beinhaltet alle benannten Caches basierend auf Strings, auf die der Worker zugreifen kann.
+
{{domxref("Client") }}
+
Repräsentiert den Gültigkeitsbereich von einem Service-Worker-Client. Ein Service-Worker-Client ist entweder ein Dokument in einem Browser-Kontext oder ein {{domxref("SharedWorker")}}, welches von einem aktiven Worker gesteuert wird.
+
{{domxref("Clients") }}
+
Repräsentiert einen Container von {{domxref("Client")}}-Objekten; die hauptsächtliche Methode, um die aktiven Service-Worker-Clients anzusteuern.
+
{{domxref("ExtendableEvent") }}
+
Erweitert die Lebensdauer der install und activate-Events, die vom {{domxref("ServiceWorkerGlobalScope")}} entfernt werden als teil des Service-Worker-Lebenszyklus. Dies versichert, dass einige Events wie z. B. das {{domxref("FetchEvent")}} nicht vom {{domxref("ServiceWorker")}}, solange sie veraltete Cache-Einträge löschen usw.
+
{{domxref("ExtendableMessageEvent") }}
+
Das Event-Objekt von einem {{event("message_(ServiceWorker)","message")}}-Event, welches von einem Service-Worker gefeuert wird.
+
{{domxref("FetchEvent") }}
+
Die Parameter, die dem {{domxref("ServiceWorkerGlobalScope.onfetch")}}-Handler übergeben werden. FetchEvent repräsentiert eine Fetch-Aktion, die vom {{domxref("ServiceWorkerGlobalScope")}} eines {{domxref("ServiceWorker")}} entfernt wird. Es beinhaltet Information über die Anfrage und der daraus resultierenden Antwort, und stellt die {{domxref("FetchEvent.respondWith", "FetchEvent.respondWith()")}}-Methode bereit. Es ermöglicht eine willkürliche Antwort, die zurück  zur kontrollierten Seite gesendet wird.
+
{{domxref("InstallEvent") }}
+
The parameter passed into the {{domxref("ServiceWorkerGlobalScope.oninstall", "oninstall")}} handler, the InstallEvent interface represents an install action that is dispatched on the {{domxref("ServiceWorkerGlobalScope")}} of a {{domxref("ServiceWorker")}}. As a child of {{domxref("ExtendableEvent")}}, it ensures that functional events such as {{domxref("FetchEvent")}} are not dispatched during installation. 
+
{{domxref("Navigator.serviceWorker") }}
+
Returns a {{domxref("ServiceWorkerContainer")}} object, which provides access to registration, removal, upgrade, and communication with the {{domxref("ServiceWorker")}} objects for the associated document.
+
{{domxref("NotificationEvent") }}
+
The parameter passed into the {{domxref("ServiceWorkerGlobalScope.onnotificationclick", "onnotificationclick")}} handler, the NotificationEvent interface represents a notification click event that is dispatched on the {{domxref("ServiceWorkerGlobalScope")}} of a {{domxref("ServiceWorker")}}.
+
{{domxref("ServiceWorker") }}
+
Represents a service worker. Multiple browsing contexts (e.g. pages, workers, etc.) can be associated with the same ServiceWorker object.
+
{{domxref("ServiceWorkerContainer") }}
+
Provides an object representing the service worker as an overall unit in the network ecosystem, including facilities to register, unregister and update service workers, and access the state of service workers and their registrations.
+
{{domxref("ServiceWorkerGlobalScope") }}
+
Represents the global execution context of a service worker.
+
{{domxref("ServiceWorkerMessageEvent")}}
+
Contains information about an event sent to a {{domxref("ServiceWorkerContainer")}} target. 
+
{{domxref("ServiceWorkerRegistration") }}
+
Represents a service worker registration.
+
{{domxref("SyncEvent")}} {{non-standard_inline}}
+
+

The SyncEvent interface represents a sync action that is dispatched on the {{domxref("ServiceWorkerGlobalScope")}} of a ServiceWorker. 

+
+
{{domxref("SyncManager")}} {{non-standard_inline}}
+
Provides an interface for registering and listing sync registrations.
+
{{domxref("WindowClient") }}
+
Represents the scope of a service worker client that is a document in a browser context, controlled by an active worker. This is a special type of {{domxref("Client")}} object, with some additional methods and properties available.
+
+ +

Spezifikationen

+ + + + + + + + + + + + + + +
SpezifikationStatusKommentar
{{SpecName('Service Workers', '')}}{{Spec2('Service Workers')}}Initial definition.
+ +

Browser-Kompatibilität

+ +
{{ CompatibilityTable() }}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(40.0)}}{{ CompatGeckoDesktop("44.0") }}{{ CompatNo() }}24{{ CompatNo() }}
install/activate events{{ CompatChrome(40.0) }}{{ CompatGeckoDesktop("44.0") }}{{ CompatNo() }}{{ CompatVersionUnknown() }}{{ CompatNo() }}
fetch event/request/
+ respondWith()
{{CompatChrome(40.0)}}{{ CompatGeckoDesktop("44.0") }}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}
caches/cache +

{{CompatChrome(42.0)}}

+
{{ CompatGeckoDesktop("39.0") }}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)Firefox OSIE PhoneOpera MobileSafari Mobile
Basic support{{CompatChrome(40.0)}}{{ CompatGeckoMobile("44.0") }}{{ CompatVersionUnknown }}{{ CompatNo() }}{{ CompatVersionUnknown() }}{{ CompatNo() }}
 install/activate events{{ CompatNo() }}{{CompatChrome(40.0)}}{{ CompatGeckoMobile("44.0") }}{{ CompatVersionUnknown }}{{ CompatNo() }}{{ CompatVersionUnknown() }}{{ CompatNo() }}
fetch event/request/
+ respondWith()
{{ CompatNo() }}{{CompatChrome(40.0)}}{{ CompatGeckoMobile("44.0") }}{{ CompatVersionUnknown }}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}
caches/cache{{ CompatNo() }}{{CompatChrome(40.0)}}{{ CompatGeckoMobile("39.0") }}{{ CompatVersionUnknown }}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}
+
+ +
+

Note: For backwards compatibility, you could choose to use service workers and AppCache on the same web app to do equivalent things (if the AppCache will support doing those things, of course.) What happens in such a case is that browsers that don’t support Service Workers will use AppCache, and those that do will ignore the AppCache and let the service worker take over.

+
+ +

Siehe auch

+ + diff --git a/files/de/web/api/service_worker_api/using_service_workers/index.html b/files/de/web/api/service_worker_api/using_service_workers/index.html new file mode 100644 index 0000000000..f45d69025f --- /dev/null +++ b/files/de/web/api/service_worker_api/using_service_workers/index.html @@ -0,0 +1,507 @@ +--- +title: Service-Worker benutzen +slug: Web/API/Service_Worker_API/Using_Service_Workers +tags: + - Anleitung + - Grundlagen +translation_of: Web/API/Service_Worker_API/Using_Service_Workers +--- +

{{ServiceWorkerSidebar}}

+ +

{{ SeeCompatTable() }}

+ +
+

Dieser Artikel informiert über die ersten Schritte mit Service-Workern, inklusive der Basisarchitektur, der Registrierung eines Service-Workers, der Installation und des Aktivierungsprozesses für einen neuen Service-Worker, Aktualisierung eines Service-Workers, Cache-Kontrolle und benutzerdefinierte Antworten, alles im Kontext von einer simplen App mit Offline-Funktionalität. 

+
+ +

Die Voraussetzung von Service-Workern

+ +

Ein großes Problem, unter dem Web-User seit Jahren leiden, ist der Verlust der Internetverbindung. Selbst die beste Webanwendung liefert eine furchtbare Benutzererfahrung, wenn sie nicht heruntergeladen werden kann. Es gab verschiedene Versuche, Technologien zu erstellen, die dieses Problem lösen (wie unsere Offline-Seite zeigt) und einige Themen konnten so angegangen werden. Das größte Problem aber ist, dass es immer noch keinen guten allgemeinen Kontroll-Mechanismus für Asset-Caching und eigene Netzwerkanfragen gibt. 
+
+ Der vorausgegangene Versuch — AppCache — schien eine gute Idee, da er der Entwicklerin erlaubte, Assets zu spezifizieren, die leicht zu cachen sein sollten. Die Technologie traf jedoch Annahmen darüber, was die Entwicklerin zu tun gedachte und schlug an mehreren Stellen fehl, wenn die Webanwendung diesen Annahmen nicht eins zu eins folgte. Mehr Details dazu finden sich in Jake Archibalds "Application Cache is a Douchebag".

+ +
+

Beachte:  Wird AppCache verwendet, um Offline-Support für eine Seite zur Verfügung zu stellen, wird seit Firefox 44 eine Warnmeldung auf der Console angezeigt, die Entwicklern statt dessen die Verwendung von Service-Workern empfiehlt ({{bug("1204581")}}).

+
+ +

Service-Worker sollen diese Probleme schließlich beheben. Ihre Syntax ist komplexer als die des AppCaches, der Vorteil ist aber, dass nun JavaScript benutzt werden kann, um die vom AppCache getroffenen Annahmen feinschrittig zu kontrollieren, was das zuvor beschriebene Problem und viele weitere löst. Mit Hilfe eines Service-Workers, kann die Webanwendung leicht aufgesetzt werden, um vorrangig gecachte Assets zu benutzen und so auch im Offline-Fall eine bestimmte Benutzererfahrung zu ermöglichen, bevor weitere Daten aus dem Netzwerk geladen werden (auch bekannt als Offline First-Ansatz). Native Apps stellen dieses Feature bereits bereit, was der Grund dafür ist, dass native Apps oft Webanwendungen vorgezogen werden.

+ +

Einrichtung zur Verwendung von Service-Workern

+ +

Viele der Eigenschaften von Service-Workern sind inzwischen in neueren Versionen unterstützender Browser standardmäßig eingestellt. Sollte der Beispielcode in einem der installierten Browser jedoch nicht funktionieren, kann die explizite Aktivierung einer Einstellung vonnöten sein:

+ + + +

Stellen Sie weiterhin sicher, dass Ihr Code über HTTPS gesendet wird — Service-Worker sind aus Sicherheitsgründen auf HTTPS beschränkt. Da GitHub (resp. GitHub Pages) HTTPS unterstüzt, ist es ein guter Ort, um Experimente zu hosten.

+ +

Grundarchitektur

+ +

+ +

Ein einfache Implementierung von Service-Workern folgt für gewöhnlich den folgenden Schritten:

+ +
    +
  1. Die URL des Service-Workers wird aufgerufen und via {{domxref("serviceWorkerContainer.register()")}} registriert.
  2. +
  3. War dies erfolgreich, wird der Service-Worker in einem {{domxref("ServiceWorkerGlobalScope")}} ausgeführt; Im Prinzip ist dies eine besondere Art von Worker-Kontext, welcher außerhalb des Threads des Hauptscriptes läuft und keinen Zugriff auf das DOM hat.
  4. +
  5. Der Service-Worker kann nun Events verarbeiten.
  6. +
  7. Die Installation des Workers wird versucht, wenn Seiten, die durch Service-Worker verwaltet werden, wiederholt besucht werden. Ein Install-Event ist immer das erste, welches an einen Service-Worker gesendet wird (Dies kann beispielsweise benutzt werden, um den Prozess zu starten, der die IndexDB befüllt und Seiten-Assets cacht). Das ist der gleiche Ablauf, der bei der Installation einer nativen oder FirefoxOS App stattfindet - alles für die Offline-Nutzung vorbereiten.
  8. +
  9. Sobald der oninstall-Handler abgeschlossen ist, wird der Service-Worker als installiert betrachtet.
  10. +
  11. Der nächste Schritt ist Aktivierung. Sobald der Service-Worker installiert wurde, erhält dieser ein activate-Event. Der Hauptnutzen von onactivate ist das Aufräumen von Ressourcen, die in vorherigen Versionen des Service-Worker-Scripts genutzt wurden.
  12. +
  13. Der Service-Worker kann nun Webseiten verwalten, aber nur wenn diese nach dem erfolgreichen Abschluss von register() aufgerufen wurden. So wird ein Dokument, welches ohne Service-Worker gestartet wurde bis zu einem Neuladen nicht von einem Service-Worker verwaltet werden.
  14. +
+ +

Promises

+ +

Promises sind ein sehr guter Mechanismus um asynchrone Operationen, deren Erfolg voneinander abhängt, auszuführen. Diese Technologie ist zentral für die Arbeitsweise von Service-Workern.
+
+ Promises ermöglichen viele verschiedene Dinge, für unseren Zweck reicht es allerdings aus zu wissen, dass, wenn eine Funktion eine Promise zurück gibt, ein .then() an das Ende des Aufrufs gehangen werden und mit Callbacks für Erfolg, Misserfolg, etc. versehen werden kann. Des Weiteren kann .catch() am Ende benutzt werden, um einen besonderen Callback für den Misserfolg hinzuzufügen.

+ +

Vergleichen wir nun die traditionelle synchrone Callback-Struktur mit ihrem asynchronen Promise-Äquivalent.

+ +

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);
+});
+ +

Im ersten Beispiel müssen wir warten, bis die myFunction() ausgeführt wird und value zurückgegeben wird bevor weiterer Code ausgeführt werden kann. Im zweiten Beispiel gibt myFunction() eine Promise für value zurück, danach kann weiterer Code ausgeführt werden. Wenn die Promise aufgelöst wird, wird der Code in then asynchron ausgeführt.
+
+ Nun zu einem echten Beispiel: Was, wenn wir Bilder dynamisch laden, aber sicher stellen wollen, dass sie erst angezeigt werden, wenn sie vollständig geladen sind? Dies ist etwas, was häufig gemacht werden soll, aber sehr kompliziert werden kann. .onload kann benutzt werden, um ein Bild erst anzuzeigen, wenn es geladen wurde. Was aber geschieht mit Events, die stattfinden, bevor wir auf diese hören können? Man könnte versuchen, dieses Problem mit Hilfe von .complete zu umgehen, was jedoch nicht betriebssicher ist und den Umgang mit mehreren Bildern gleichzeitig nicht abdeckt. Auch ist dieser Ansatz weiterhin synchron und blockiert somit den Haupt-Thread.
+
+ Wir können jedoch stattdessen eine eigene Promise bauen, die diesen Fall abdeckt. (Siehe unser Promises-Test-Beispiel für den entsprechenden Quellcode, oder hier für eine Liveanwendung.)

+ +

{{note("Eine echte Service-Worker-Implementierung würde Caching und das onfetch-Event statt der überholten XMLHttpRequest API benutzen. Diese Features wurden hier nicht benutzt, um den Fokus auf Promises setzen zu können.")}}

+ +
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('Bild wurde nicht geladen; Fehlercode:' + request.statusText));
+      }
+    };
+
+    request.onerror = function() {
+      reject(Error('Ein Netzwerkfehler ist aufgetreten.'));
+    };
+
+    request.send();
+  });
+}
+ +

Wir geben eine neue Promise mit Hilfe des Promise()-Konstruktors zurück, der als Parameter eine Callback-Funktion mit resolve- und reject- Parametern erhält. Innerhalb dieser Funktion müssen wir definieren, was passieren muss, dass die Promise erfolgreich aufgelöst oder zurückgewiesen wird — In diesem Fall also entweder einen 200 OK Status zurückgegeben bekommen oder nicht — und dann bei Erfolg resolve und bei Misserfolg reject aufzurufen. Der restliche Inhalt dieser Funktion sind Schritte zum Umgang mit XHR, über die wir uns im Moment keine Gedanken machen müssen.

+ +

Wenn wir beim Aufruf der imgLoad()-Funktion angelangt sind, rufen wir diese mit der URL zu dem Bild, welches wir laden möchten, wie erwartet auf, der restliche Code ist jedoch ein bisschen anders:

+ +
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);
+});
+ +

Die then()-Methode wird an das Ende des Funktionsaufrufes gehangen, und enthält zwei Funktionen – die erste wird ausgeführt, wenn die Promise aufgelöst wird, die zweite, wenn sie zurückgewiesen wird. Im Auflösungsfall zeigen wir das Bild innerhalb von myImage an und fügen es an den body an (Das Argument der then()-Funktion ist die request.response innerhalb der resolve-Methode des Promises); im Zurückweisungsfall geben wir einen Fehler in der Konsole aus.

+ +

Dies alles geschieht asynchron.

+ +
+

Beachte: Promises können aneinandergekettet werden, zum Beispiel:
+ myPromise().then(success, failure).then(success).catch(failure);

+
+ +
+

Beachte: Weitere Informationen zu Promises finden sich in Jake Archibalds Artikel JavaScript Promises: there and back again.

+
+ +

Service-Worker Demo

+ +

Um die Grundlagen der Registrierung und Installation eines Service-Workers zu demonstrieren, haben wir eine kleine Demo namens sw-test geschaffen, die eine überschaubare Star-Wars-Lego-Bildergalerie ist. Sie nutzt eine Promise-unterstützte Funktion um Bilddaten von einem JSON-Objekt zu lesen und diese Bilder mit Hilfe von Ajax zu laden, bevor sie untereinander auf der Webseite angezeigt werden. Die Anwendung ist statisch und einfach gehalten. Sie registriert, installiert und aktiviert des Weiteren einen Service-Worker und cacht die erforderlichen Dateien für die Offline-Nutzung, sollten weitere Aspekte dieser Spezifikation bei den aufrufenden Browsern aktiviert sein.

+ +


+
+
+ Der Quellcode ist auf GithHub zu finden, eine Live-Version kann hier betrachtet werden. Der Aspekt, den wir hier betrachten wollen, ist die Promise (siehe app.js Zeilen 17-42), die eine modifizierte Version dessen ist, was in der Promises Test Demo zu lesen war. Die Unterschiede sind die folgenden:

+ +
    +
  1. Im Original haben wir nur eine URL zu einem Bild, welches wir laden wollen, hineingereicht. In dieser Version reichen wir ein JSON-Fragment hinein, welches alle Daten für ein einzelnes Bild beinhaltet (in image-list.js kann ein Blick darauf geworfen werden). Das geschieht, weil wegen der Asynchronität die gesamten Daten für jedes Auflösen der Promise in in diese hineingereicht werden müssen. Würde nur die URL hineingereicht werden und versucht werden, während der for()-Schleife, auf andere Dinge im JSON zuzugreifen, schlüge dies fehl, da die Promise nicht zeitgleich mit dem Abschluss der Iteration auflösen würde, da dies ein synchroner Prozess ist.
  2. +
  3. Wir lösen die Promise des Weiteren mit einem Array auf, da wir den geladenen Bild-Blob, aber auch Bildname, Bildnachweis und Alt-Text später der auflösenden Funktion zur Verfügung stellen wollen. (siehe app.js Zeilen 26-29). Promises lösen mit einem einzigen Argument auf, werden also mehrere Werte gebraucht, muss dies über ein Array bzw. Objekt gelöst werden.
  4. +
  5. Um auf die Werte der aufgelösten Promise zuzugreifen, greifen wir auf eben jene Funktion zu. (siehe app.js Zeilen 55-59.) Dies mag auf den ersten Blick seltsam erscheinen, ist aber die korrekte Handhabung von Promises.
  6. +
+ +

Service-Worker auf die Bühne, bitte!

+ +

Auf geht's zu Service-Workern!

+ +

Service-Worker registrieren

+ +

Der erste Code-Block in der JavaScript-Datei unserer App — app.js — sieht wie folgt aus. Dies ist unser Startpunkt für die Nutzung von Service-Workern.

+ +
if ('serviceWorker' in navigator) {
+  navigator.serviceWorker.register('/sw-test/sw.js', { scope: '/sw-test/' }).then(function(reg) {
+    // Registrierung erfolgreich
+    console.log('Registrierung erfolgreich. Scope ist ' + reg.scope);
+  }).catch(function(error) {
+    // Registrierung fehlgeschlagen
+    console.log('Registrierung fehlgeschlagen mit ' + error);
+  });
+};
+ +
    +
  1. Der äußere Block kümmert sich um die Feature-Erkennung um sicher zu stellen, dass Service-Worker unterstützt werden, bevor einer registriert wird.
  2. +
  3. Als nächstes nutzen wir die {{domxref("ServiceWorkerContainer.register()") }}-Funktion, um den Service Worker für diese Seite zu registrieren. Dieser ist nur eine JavaScript-Datei innerhalb unserer App. (Beachte, dass die URL der Datei relativ zum Ursprung ist, und nicht zur JavaScript-Datei, die sie referenziert.)
  4. +
  5. Der scope Parameter ist optional, und kann benutzt werden, um den Teil der. Applikation einzuschränken, den der Service-Worker kontrollieren soll. In diesem Fall, haben wir '/sw-test/' spezifiziert, was alle Inhalte unter dem App-Ursprungsverzeichnis beinhaltet. Wird der Parameter weggelassen, würde standardmäßig dieses Verzeichnis gewählt werden. Wir haben es hier zu Anschauungszwecken jedoch spezifiziert..
  6. +
  7. Die .then() Promise-Funktion wird genutzt, um den Erfolgsfall an unsere Promise-Struktur zu hängen. Wenn die Promise erfolgreich auflöst, wird der Programmcode innerhalb dieser Funktion ausgeführt.
  8. +
  9. Zuletzt fügen wir die.catch()-Funktion ans Ende an, die ausgeführt wird, sollte die Promise zurückgewiesen werden.
  10. +
+ +

Jetzt ist ein Service-Worker registriert, der in einem Worker-Kontext läuft und daher keinen Zugriff auf das DOM hat. Code im Service-Worker wird außerhalb der normalen Seiten ausgeführt, um deren Laden zu kontrollieren.
+
+ Ein einzelner Service-Worker kann viele Seiten kontrollieren. Wird eine Seite innerhalb des spezifizierten Codes geladen, wird der Service-Worker für diese eingerichtet und nimmt seine Arbeit auf. Es sollte daher nicht vergessen werden, dass vorsichtig mit globalen Variablen im Service-Worker-Script umgegangen werden muss: Jede Seite im Scope hat den selben Worker, mit dem sie arbeitet.

+ +
+

Beachte: Service-Worker funktionieren wie Proxy-Server, was es unter anderem erlaubt, Netzwerkanfragen und -antworten zu modifizieren und mit Objekten aus dem Cache zu ersetzen.

+
+ +
+

Beachte: Eine gute Sache an Service-Workern ist, dass, wenn Feature-Erkennung wie im obigen Beispiel verwendet wird, Browser, die Service-Worker nicht unterstützen, die App dennoch normal und wie erwartet benutzen können. Wenn weiterhin AppCache und Service-Worker gemeinsam auf einer Seite benutzt werden, werden Browser, die AppCache aber nicht Service-Worker unterstützen, ersteres benutzen. Browser die beides unterstützen, werden AppCache zu Gunsten von Service-Workern ignorieren.

+
+ +

Wieso schlägt die Registrierung meines Service Workers fehl?

+ +

Dies kann aus folgenden Gründen passieren:

+ +
    +
  1. Die Applikation läuft nicht unter HTTPS
  2. +
  3. Der Pfad zur Service-Worker-Datei ist nicht korrekt beschrieben — er muss relativ zum Ursprung geschrieben sein, nicht relativ zum Wurzelverzeichnis der App. In unserem Beispiel liegt der Worker unter https://mdn.github.io/sw-test/sw.js, wohingegen das Wurzelverzeichnis der App https://mdn.github.io/sw-test/ ist. Der Pfad muss also als /sw-test/sw.js, geschrieben werden, und nicht als /sw.js.
  4. +
  5. Der Service-Worker, auf den verwiesen wird, hat einen anderen Ursprung als die App. Auch das ist nicht gestattet.
  6. +
+ +

Weiterhin zu beachten:

+ + + +

Installation und Aktivierung: Füllen des Caches

+ +

Nachdem der Service-Worker registriert wurde, versucht der Browser den Service-Worker für die entsprechende Seite zu installieren und zu aktivieren.
+
+ Das Install-Event wird abgesetzt wenn eine Installation erfolgreich abgeschlossen wurde. Dieses Event wird für gewöhnlich dazu genutzt, den Offline-Cache des Browsers mit den Assets zu befüllen, die benötigt werden, damit die App offline laufen kann. Um das zu erreichen, nutzen wir die Storage-API der Service-Worker — {{domxref("cache")}} — ein globales Objekt des Service-Workers, welches uns erlaubt Assets, die durch Netzwerkantworten geliefert wurden, zu speichern. Diese API arbeitet ähnlich wie der Browser interne Cache, ist allerdings Domain spezifisch und besteht, bis Gegenteiliges gesagt wird, was erneut volle Kontrolle erlaubt.

+ +
+

Beachte: Die Cache API ist nicht in jedem Browser unterstützt. (Siehe auch den Abschnitt {{anch("Browserkompabilität")}} für weitere Informationen.) Soll sie jetzt genutzt werden, kann ein Polyfill in Betracht gezogen werden, wie er beispielsweise in Googles Topeka Demo enthalten ist, oder die Assets in IndexedDB gespeichert werden.

+
+ +

Wir beginnen diesen Abschnitt mit einem Blick auf ein Code-Beispiel — Das ist der erste Block in unserem 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. Hier wird dem Service-Worker (mit Hilfe von this) ein installEvent-Listener hinzugefügt, und die {{domxref("ExtendableEvent.waitUntil()") }}-Methode dem Event angehängt — das stellt sicher, dass der Service-Worker nicht installiert wird, bis der Code innerhalb von waitUntil() erfolgreich ausgeführt wurde.
  2. +
  3. Innerhalb von waitUntil() benutzen wir die caches.open()-Methode um einen neuen Cache mit dem Namen v1 zu erstellen, welcher die erste Version des Ressourcenspeichers unserer Seite sein wird. Das gibt eine Promise für den erstellten Cache zurück; sobald diese aufgelöst ist, rufen wir eine Funktion auf, die wiederum addAll() auf dem erstellten Cache aufruft und als Parameter einen Array mit zum Ursprung relativen URLs der zu cachenden Ressourcen enthält.
  4. +
  5. Sollte die Promise zurückgewiesen werden, schlägt die Installation fehl und der Worker tut nichts. Das ist in Ordnung und bietet die Möglichkeit, den Code zu korrigieren und es bei der nächsten Registrierung erneut zu versuchen.
  6. +
  7. Nach erfolgreicher Installation wird der Service-Worker aktiviert. Wurde der Service-Worker zum ersten mal installiert und aktiviert ist dies nicht weiter von Bedeutung, aber wichtig, wenn der Service-Worker aktiviert wird. (Siehe den Abschnitt {{anch("Aktualisieren des Service-Workers") }} im späteren Verlauf.)
  8. +
+ +
+

Beachte: localStorage funktioniert ähnlich wie der Service-Worker-Cache, ist aber synchron und daher in Service-Workern nicht gestattet.

+
+ +
+

Beachte: IndexedDB kann, wenn nötig, innerhalb eines Service-Workers benutzt werden.

+
+ +

Eigene Antworten auf Netzwerkanfragen

+ +

Da jetzt die Assets der Seite gecacht wurden, kann nun den Service-Workern mitgeteilt werden, was sie mit dem gecachten Inhalt tun sollen. Dies geschieht mit Hilfe des fetch-Events.

+ +

Ein fetch-Event wird jedes Mal abgesetzt, wenn eine Ressource, die vom Service-Worker kontrolliert wird (also die Dokumente innerhalb seines Scopes sowie die dort referenzierten Ressourcen), geladen wird.  (Wenn also index.html eine Cross-Origin-Anfrage an ein eingebettetes Bild absetzt, geht auch das durch den Service-Worker.)

+ +

Ein fetch Event-Listener kann dem Service-Worker hinzugefügt, und die respondWith()-Methode des Events aufgerufen werden, um die HTTP-Antworten abzufangen und mit unseren eigenen zu ersetzen.

+ +
this.addEventListener('fetch', function(event) {
+  event.respondWith(
+    // Hier eigene Antworten
+  );
+});
+ +

Es kann damit begonnen werden, jedes Mal mit der Ressource zu antworten, deren URL der der Netzwerkanfrage entspricht:

+ +
this.addEventListener('fetch', function(event) {
+  event.respondWith(
+    caches.match(event.request)
+  );
+});
+ +

caches.match(event.request) erlaubt uns, jede Ressource, die vom Netzwerk angefragt wird, mit der entsprechenden Ressource des Caches zu ersetzen, so diese verfügbar ist. Der Abgleich geschieht wie bei normalen HTTP-Anfragen über URLs und Header.

+ +

Betrachten wir einige weitere Optionen, die wir haben, wenn wir unsere eigenen Antworten definieren wollen (siehe auch die Fetch-API Dokumentation für weitere Informationen über {{domxref("Request")}}- und {{domxref("Response")}}-Objekte.)

+ +
    +
  1. +

    Der {{domxref("Response.Response","Response()")}}-Konstruktor  erlaubt uns das Erstellen einer benutzerdefinierten Antwort. In diesem Fall geben wir eine einfache Zeichenkette zurück:

    + +
    new Response('Hallo vom freundlichen Service-Worker!');
    +
  2. +
  3. +

    Das folgende komplexere Response-Beispiel zeigt, dass optional eine Anzahl an Headern in der Antwort gesetzt werden können, die die Standard HTTP-Responce-Header emulieren. Hier wird dem Browser nut der Content-Type unserer künstlichen Antwort mitgeteilt:

    + +
    new Response('<p>Hallo from freundlichen Service-Worker!</p>', {
    +  headers: { 'Content-Type': 'text/html' }
    +})
    +
  4. +
  5. +

    Wenn im Cache kein Treffer gefunden wurde, könnte der Browser angewiesen werden, die standardmäßigen Netzwerkanfrage mit {{domxref("GlobalFetch.fetch","fetch")}} auszuführen, um die Ressource aus dem Netzwerk zu laden, wenn dieses verfügbar ist:

    + +
    fetch(event.request)
    +
  6. +
  7. +

    Wenn es keinen Treffer gab und auch das Netzwerk nicht verfügbar ist, kann die Anfrage mit einer Ausweichseite beantwortet werden, indem {{domxref("CacheStorage.match","match()")}} folgendermaßen verwendet wird:

    + +
    caches.match('/fallback.html');
    +
  8. +
  9. +

    Viele Informationen über jeden Request können erhalten werden, indem Parameter des {{domxref("Request")}}-Objekts, welches vom {{domxref("FetchEvent")}} zurückgegeben wird, aufgerufen werden.

    + +
    event.request.url
    +event.request.method
    +event.request.headers
    +event.request.body
    +
  10. +
+ +

Umgang mit fehlgeschlagenen Cache-Anfragen

+ +

caches.match(event.request)ist hilfreich, wenn es einen Treffer im Service-Worker-Cache gibt. Was aber, wenn das nicht der Fall ist? Stellten wir keine Möglichkeit zur Behandlung einer scheiternden Cache-Anfrage bereit, würde unsere Promise zurückgewiesen werden und wir würden einem Netzwerkfehler gegenüber stehen, wenn es keinen Treffer im Cache gibt.

+ +

Glücklicherweise erlaubt die Promise basierte Struktur des Service-Workers weitere Optionen bereitzustellen. Beispielsweise:

+ +
this.addEventListener('fetch', function(event) {
+  event.respondWith(
+    caches.match(event.request).catch(function() {
+      return fetch(event.request);
+    })
+  );
+});
+ +

Falls die Promise zurückgewiesen wird, gibt die catch()-Funktion die Standard-Netzwerkanfrage für die Ressource zurück, was es erlaubt, diese vom Server zu laden, sollte eine Netzwerkverbindung bestehen.

+ +

Ein weiterer Weg wäre, die Ressource nicht bloß aus dem Netzwerk zu laden, sondern für zukünftige Anfragen im Cache zu speichern, damit diese ebenfalls offline verwendet werden können. Das bedeutet, sollten weitere Bilder zur Star-Wars-Galerie hinzugefügt werden, kann unsere App diese laden und cachen. Es würde folgendermaßen implementiert werden:

+ +
this.addEventListener('fetch', function(event) {
+  event.respondWith(
+    caches.match(event.request).catch(function() {
+      return fetch(event.request).then(function(response) {
+        return caches.open('v1').then(function(cache) {
+          cache.put(event.request, response.clone());
+          return response;
+        });
+      });
+    })
+  );
+});
+ +

Wir geben an dieser Stelle die Standard-Netzwerkanfrage mit return fetch(event.request) zurück, die wiederum eine Promise zurückgibt. Wenn diese Promise aufgelöst wird, reagieren wir mit einer Funktion, die unseren Cache mit caches.open('v1') öffnet, was eine weitere Promise zurückgibt. Wenn diese auflöst, wird cache.put() benutzt, um die Ressource dem Cache hinzuzufügen. Diese wird aus event.request gezogen, die Netzwerkantwort mit response.clone() kopiert und dem Cache hinzugefügt. Die Kopie wird gespeichert und die Original-Netzwerkantwort an den Browser und somit an die Seite, die die Anfrage gestellt hat, zurückgegeben.

+ +

Warum das alles? Der Datenstrom von Netzwerkanfrage und -antwort kann nur ein einziges Mal gelesen werden. Damit die Netzwerkantwort an den Browser zurückgegeben werden und trotzdem auch im Cache gespeichert werden kann, muss sie kopiert werden. Dadurch kann das Original an den Browser gereicht und die Kopie im Cache gespeichert werden. Original und Kopie werden somit jeweils nur einmal gelesen.

+ +

Zuletzt bleibt noch das Problem, was passieren soll, wenn es weder einen Treffer im Cache noch eine verfügbare Netzwerkverbindung gibt. Zur Zeit schlägt unsere Anfrage an die Ressource fehl. Wenn wir eine Ausweichlösung bereitstellen, werden, egal was passiert, die Nutzer eine Antwort bekommen:

+ +
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');
+    })
+  );
+});
+ +

Wir haben uns an dieser Stelle für ein Ausweichbild entschieden, da die einzigen Anfragen, die potentiell fehlschlagen, die für neue Bilder in der Galerie sein werden. Um alles andere wurde sich bereits während des install-Events der Installation gekümmert.

+ +

Aktualisieren des Service-Workers

+ +

Wurde der Service-Worker bereits installiert, aber eine neue Version bei Neuladen der Seite bereitgestellt werden, wird dieser neue Worker im Hintergrund installiert, jedoch noch nicht aktiviert. Das geschieht erst dann, wenn keine der Seiten, die den alten Worker nutzen, mehr geladen werden. Sobald dies der Fall ist, wird der neue Service-Worker aktiviert.

+ +

Damit dies geschehen kann, muss derinstall-Event-Listener im neuen Service-Worker ungefähr folgendermaßen angepasst werden (Augenmerk auf die neue Versionsnummer):

+ +
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',
+
+             …
+
+              // hier können weitere neue Ressourcen stehen...
+      ]);
+    });
+  );
+});
+ +

Während dies alles geschieht, ist weiterhin die vorherige Version des Service-Workers für die Verwaltung der Anfragen verantwortlich und die neue Version wird im Hintergrund installiert. Der neue Cache hat in diesem Beispiel den Namen v2, so dass der Cache mit dem Namen v1 nicht beeinträchtigt wird.

+ +

Wenn keine Seiten mehr die aktuelle Version benutzen, wird der neue Worker aktiviert und verwaltet die Netzwerkanfragen.

+ +

Löschen des alten Caches

+ +

Es steht weiterhin ein activate-Event zur Verfügung. Es wird generell genutzt, um Dinge abzuhandeln, die die alte Version stark beeinträchtigt hätten, würden sie zu deren Laufzeit ausgeführt werden. Dies betrifft zum Beispiel das Löschen der alten Caches. Das Event ist auch nützlich, um Daten zu löschen, die nicht mehr gebraucht werden und so zu verhindern, dass zu viel Speicherplatz verbraucht wird — jeder Browser hat eine feste Obergrenze für die Menge an Cache-Speicherplatz, die ein Service-Worker nutzen kann. Der Browser selbst verwaltet den Speicherplatz an sich selbstständig, aber es kann passieren, dass der Cache-Speicherplatz für eine Seite gelöscht wird, denn wenn der Browser Daten dieser Art löscht, dann entweder alle oder keine Daten der Seite.

+ +

Promises, die waitUntil() hineingereicht werden, blockieren weitere Events bis diese abgearbeitet wurden, so dass sicher gestellt werden kann, dass alle Aufräumarbeiten abgeschlossen sind, bevor die erste Netzwerkanfrage an den neuen Cache gestellt wird.

+ +
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);
+        }
+      }));
+    })
+  );
+});
+ +

Entwicklertools

+ +

Chrome hat chrome://inspect/#service-workers, wo Aktivität und Speicherplatz der aktuellen Service-Worker eingesehen werden können, und chrome://serviceworker-internals, wo mehr Details zu finden sind und Service-Worker gestartet, beendet und der Fehlersuche unterworfen werden können. Zukünftige Versionen werden zusätzlich Mittel zur Netzwerkdrosselung und einen Offline-Modus bereitsellen, um schlechte oder nicht vorhandene Netzwerkverbindungen zu simulieren.

+ +

Auch Firefox hat die Entwicklung nützlicher Werkzeuge in Bezug auf Service-Worker begonnen:

+ + + +

Spezifikationen

+ + + + + + + + + + + + + + +
SpezifikationStatusKommentar
{{SpecName('Service Workers', '')}}{{Spec2('Service Workers')}}Initiale Definition.
+ +

Browserkompatibilität

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Grundlegende Unterstüzung{{CompatChrome(40.0)}}{{ CompatGeckoDesktop("33.0") }}{{CompatNo}}24{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)Firefox OSIE PhoneOpera MobileSafari Mobile
Grundlegende Unterstüzung{{CompatNo}}{{CompatChrome(40.0)}}{{ CompatVersionUnknown }}{{ CompatVersionUnknown }}{{CompatNo}}{{ CompatVersionUnknown() }}{{CompatNo}}
+
+ +

Siehe auch

+ + diff --git a/files/de/web/api/serviceworker/index.html b/files/de/web/api/serviceworker/index.html new file mode 100644 index 0000000000..38d160b96b --- /dev/null +++ b/files/de/web/api/serviceworker/index.html @@ -0,0 +1,103 @@ +--- +title: ServiceWorker +slug: Web/API/ServiceWorker +translation_of: Web/API/ServiceWorker +--- +
{{APIRef("Service Workers API")}}
+ +

Die ServiceWorker-Schnittstelle der Service Worker-API stellt einen Verweis auf einen Serviceworker bereit. Mehrere "Glossary"-Glossar-("Browsing-Kontexte", "Browsing-Kontexte") (z. B. .pages, Arbeitskräfte usw.) können demselben Service-Worker zugeordnet werden, jeder durch ein eindeutiges Objekt.ServiceWorker

+ +

Ein Objekt ist in der Eigenschaft ""ServiceWorkerRegistration.active"" und in der Eigenschaft ""ServiceWorkerContainer.controller"" verfügbar – dies ist ein Service-Worker, der aktiviert wurde und die Seite steuert (der Service-Worker wurde erfolgreich registriert, und die gesteuerte Seite wurde neu geladen).)ServiceWorker

+ +

Die Schnittstelle wird eine Reihe von Lebenszyklusereignissen – und – und funktionalen Ereignissen einschließlich ausgelöst. Einem Objekt ist ein Objekt zugeordnet, dem der Lebenszyklus von "ServiceWorker.state") zugeordnet ist.ServiceWorkerinstallactivatefetchServiceWorker

+ +

Properties

+ +

The ServiceWorker interface inherits properties from its parent, {{domxref("Worker")}}.

+ +
+
{{domxref("ServiceWorker.scriptURL")}} {{readonlyinline}}
+
Returns the serialized script URL defined as part of {{domxref("ServiceWorkerRegistration")}}. The URL must be on the same origin as the document that registers the .ServiceWorkerServiceWorker
+
{{domxref("ServiceWorker.state")}} {{readonlyinline}}
+
Returns the state of the service worker. It returns one of the following values: , , , or .installinginstalled,activatingactivatedredundant
+
+ +

Event handlers

+ +
+
{{domxref("ServiceWorker.onstatechange")}} {{readonlyinline}}
+
An {{domxref("EventListener")}} property called whenever an event of type is fired; it is basically fired anytime the {{domxref("ServiceWorker.state")}} changes.statechange
+
+ +

Methods

+ +

The ServiceWorker interface inherits methods from its parent, {{domxref("Worker")}}, with the exception of {{domxref("Worker.terminate")}} — this should not be accessible from service workers.

+ +

Examples

+ +

This code snippet is from the service worker registration-events sample (live demo). The code listens for any change in the {{domxref("ServiceWorker.state")}} and returns its value.

+ +
if ('serviceWorker' in navigator) {
+    navigator.serviceWorker.register('service-worker.js', {
+        scope: './'
+    }).then(function (registration) {
+        var serviceWorker;
+        if (registration.installing) {
+            serviceWorker = registration.installing;
+            document.querySelector('#kind').textContent = 'installing';
+        } else if (registration.waiting) {
+            serviceWorker = registration.waiting;
+            document.querySelector('#kind').textContent = 'waiting';
+        } else if (registration.active) {
+            serviceWorker = registration.active;
+            document.querySelector('#kind').textContent = 'active';
+        }
+        if (serviceWorker) {
+            // logState(serviceWorker.state);
+            serviceWorker.addEventListener('statechange', function (e) {
+                // logState(e.target.state);
+            });
+        }
+    }).catch (function (error) {
+        // Something went wrong during registration. The service-worker.js file
+        // might be unavailable or contain a syntax error.
+    });
+} else {
+    // The current browser doesn't support service workers.
+}
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Service Workers', '#serviceworker', 'ServiceWorker')}}{{Spec2('Service Workers')}}Initial definition.
+ +

Browser compatibility

+ +
+ + +

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

+
+ +

See also

+ + diff --git a/files/de/web/api/serviceworkercontainer/index.html b/files/de/web/api/serviceworkercontainer/index.html new file mode 100644 index 0000000000..2899d05b7c --- /dev/null +++ b/files/de/web/api/serviceworkercontainer/index.html @@ -0,0 +1,158 @@ +--- +title: ServiceWorkerContainer +slug: Web/API/ServiceWorkerContainer +tags: + - API + - Draft + - Interface + - NeedsTranslation + - Offline + - Reference + - Service Workers + - ServiceWorkerContainer + - TopicStub + - Workers +translation_of: Web/API/ServiceWorkerContainer +--- +

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

+ +

The ServiceWorkerContainer interface of the 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(scriptURL, scope[, base])")}} 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 if the request is a force refresh (Shift + refresh) or if there is no active worker.
+
+ +
+
{{domxref("ServiceWorkerContainer.ready")}} {{readonlyinline}}
+
Defines whether a service worker is ready to control a page or not. It returns a {{jsxref("Promise")}} that will never reject, which resolves to a {{domxref("ServiceWorkerRegistration")}} with an {{domxref("ServiceWorkerRegistration.active")}} worker.
+
+ +

Event handlers

+ +
+
{{domxref("ServiceWorkerContainer.oncontrollerchange")}}
+
An event handler fired whenever a {{Event("controllerchange")}} event occurs — when the document's associated {{domxref("ServiceWorkerRegistration")}} acquires a new {{domxref("ServiceWorkerRegistration.active")}} worker.
+
{{domxref("ServiceWorkerContainer.onerror")}}
+
An event handler fired whenever an {{Event("error")}} event occurs in the associated service workers.
+
{{domxref("ServiceWorkerContainer.onmessage")}}
+
An event handler 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 URL 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")}}s associated with a ServiceWorkerContainer in an array.  If the method can't return {{domxref("ServiceWorkerRegistration")}}s, it returns a Promise
+
+ +

Examples

+ +

This code snippet is from the service worker fallback-response sample (see fallback-response live). The code checks to see if the browser supports service workers. Then 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) {
+  navigator.serviceWorker.register('service-worker.js', {scope: './'}).then(function() {
+    if (navigator.serviceWorker.controller) {
+      document.querySelector('#status').textContent = 'The service worker is currently handling network operations.';
+      showRequestButtons();
+    } else {
+      document.querySelector('#status').textContent = 'Please reload this page to allow the service worker to handle network operations.';
+    }
+  }).catch(function(error) {
+    document.querySelector('#status').textContent = error;
+  });
+} else {
+  var aElement = document.createElement('a');
+  aElement.href = 'http://www.chromium.org/blink/serviceworker/service-worker-faq';
+  aElement.textContent = 'unavailable';
+  document.querySelector('#status').appendChild(aElement);
+}
+ +

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.0)}}{{ CompatGeckoDesktop("44.0") }}{{CompatNo}}24{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatUnknown}}{{ CompatGeckoMobile("44.0") }}{{ CompatVersionUnknown }}{{CompatNo}}{{CompatUnknown}}{{CompatNo}}{{CompatUnknown}}
+
+ +

See also

+ + diff --git a/files/de/web/api/serviceworkercontainer/register/index.html b/files/de/web/api/serviceworkercontainer/register/index.html new file mode 100644 index 0000000000..e900e8085c --- /dev/null +++ b/files/de/web/api/serviceworkercontainer/register/index.html @@ -0,0 +1,122 @@ +--- +title: ServiceWorkerContainer.register() +slug: Web/API/ServiceWorkerContainer/register +translation_of: Web/API/ServiceWorkerContainer/register +--- +

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

+ +

Die register() Methode der ServiceWorkerContainer Schnittstelle erstellt oder aktualisiert eine ServiceWorkerRegistration für die gegebene scriptURL

+ +

Nach erfolgreicher Registrierung verwendet die Service Worker Registrierung die übergebene scriptURL und ihren Bereich für den Navigationsabgleich. Die Methode gibt ein Promise zurück, welches zu einer ServiceWorkerRegistration aufgelöst wird. Die Funktion kann bedingungslos aufgerufen werden - Es muss vorher nicht kontrolliert werden, ob eine aktive Registrierung vorhanden ist.

+ +

Es entstehen häufig Verwirrungen über die Bedeutung und Verwendung des scope. Da ein ServiceWorker keinen größeren Bereich abdecken kann als seinen einen Pfad, sollte man den Parameter nur verwenden, wenn man einen kleineren Bereich als den Standardbereich abdecken will.

+ +

Syntax

+ +
ServiceWorkerContainer.register(scriptURL, options).then(function(ServiceWorkerRegistration) {
+  // Do something with ServiceWorkerRegistration.
+});
+ +

Parameter

+ +
+
scriptURL
+
Die Url des Service Workers Scripts.
+
options {{optional_inline}}
+
Ein Object, welches verschiedene Registrierungsoptionen beinhaltet. Zur Zeit stehen folgende Optionen zur Verfügung: +
    +
  • scope: Ein USVString, welcher eine URL darstellt, die zur Festlegung des Bereiches des Service Workers verwendet wird. Dies ist normalerweise eine relative URL. Der Standardwert ist die URL, die man bekommen würde, wenn man './' mit dem Pfad des Service Worker Scripts verwenden würde.
  • +
+
+
+ +

Rückgabewert

+ +

Ein Promise, welches zu einem ServiceWorkerRegistration Objekt aufgelöst wird.

+ +

Beispiele

+ +
if ('serviceWorker' in navigator) {
+  navigator.serviceWorker.register('service-worker.js', {scope: './'}).then(function(registration) {
+    document.querySelector('#status').textContent = 'succeeded';
+  }).catch(function(error) {
+    document.querySelector('#status').textContent = error;
+  });
+} else {
+  // Der verwendete Browser unterstützt Service Worker nicht.
+  var aElement = document.createElement('a');
+  aElement.href = 'http://www.chromium.org/blink/serviceworker/service-worker-faq';
+  aElement.textContent = 'unavailable';
+  document.querySelector('#status').appendChild(aElement);
+}
+ +

Spezifikationen

+ + + + + + + + + + + + + + +
SpezifikationStatusKommentar
{{SpecName('Service Workers', '#service-worker-container', 'ServiceWorkerContainer')}}{{Spec2('Service Workers')}}Initiale Definition.
+ +

Browserkompatiblität

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(40.0)}}{{ CompatGeckoDesktop("44.0") }}{{CompatNo}}24{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatUnknown}}{{ CompatGeckoMobile("44.0") }}{{ CompatVersionUnknown }}{{CompatNo}}{{CompatUnknown}}{{CompatNo}}{{CompatChrome(40.0)}}
+
diff --git a/files/de/web/api/sharedworker/index.html b/files/de/web/api/sharedworker/index.html new file mode 100644 index 0000000000..52ecc8075b --- /dev/null +++ b/files/de/web/api/sharedworker/index.html @@ -0,0 +1,117 @@ +--- +title: SharedWorker +slug: Web/API/SharedWorker +tags: + - API + - Interface + - Reference + - SharedWorker + - WebWorkers + - Workers +translation_of: Web/API/SharedWorker +--- +
{{APIRef("Web Workers API")}}
+ +

Das SharedWorker Interface repräsentiert eine spezielle Art von Worker, auf welchen durch mehrere Kontexte zugegeriffen werden kann. Hier kann es sich um verschiedene Tabs, iFrames oder auch Worker handeln. Diese implementieren ein anderes Interface als dedicated Worker und haben einen anderen Global Scope {{domxref("SharedWorkerGlobalScope")}}.

+ +
+

Note: Wenn auf einen SharedWorker von mehreren Browser Kontexten aus zugegriffen wird müssen all diese denselben Urpsrung haben. (Dasselbe Protocol, Host und Port)

+
+ +

Konstruktoren

+ +
+
{{domxref("SharedWorker.SharedWorker", "SharedWorker()")}}
+
Erstellt einen Shared Web Worker, der ein Script zu einer angegebenen URL ausführt.
+
+ +

Eigenschaften

+ +

Erbt Eigenschaften von dem Parent {{domxref("EventTarget")}} und implementiert Eigenschaften von {{domxref("AbstractWorker")}}.

+ +
+
{{domxref("AbstractWorker.onerror")}}
+
Ist ein{{domxref("EventListener")}} der immer aufgerufen wird wenn ein {{domxref("ErrorEvent")}} vom Typ error durch den Worker läuft.
+
{{domxref("SharedWorker.port")}} {{readonlyInline}}
+
Returnt ein {{domxref("MessagePort")}} Objekt, welches zum Kommunizieren und Kontrollieren des Shared Workers verwendet wird.
+
+ +
+
+ +

Methoden

+ +

Erbt Methoden von dem Parent {{domxref("EventTarget")}} und implementiert Methoden von {{domxref("AbstractWorker")}}.

+ +

Beispiel

+ +

In unserem Grundlegenden Shared Worker Beispiel (Shared Worker ausführen), haben wir zwei HTML Seiten, von denen beide etwas JavaScript verwenden um simple Kalkulationen auszuführen. Die verschiedenen Skripte verwenden dasselbe Worker File um die Kalkulation durchzuführen. Beide können auf dieses zugreifen, auch wenn diese in verschiedenen Fenstern ausgeführt werden.

+ +

Das folgende Code Beispiel zeigt das Erstellen eines SharedWorker Objekts unter der Verwendung des {{domxref("SharedWorker.SharedWorker", "SharedWorker()")}} Konstruktors. Beide Skripte enthalten:

+ +
var myWorker = new SharedWorker('worker.js');
+
+ +

Beide Skripte greifen dann auf den Worker durch ein {{domxref("MessagePort")}} Objekt zu, welches mithilfe von {{domxref("SharedWorker.port")}} erstellt wurde. Wenn das onmessage Event mithilfe von addEventListener angehängt wurde, wird der Port automatisch gestartet mittels der start() Methode:

+ +
myWorker.port.start();
+ +

Wenn der Port gestartet ist senden beide Skripte Nachrichten an den Worker und behandeln die empfangenen Nachrichten von port.postMessage() und port.onmessage:

+ +
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');
+}
+ +

Innerhalb des Workers verwenden wird den {{domxref("SharedWorkerGlobalScope.onconnect")}} Handler um uns an den oben genannten Port zu verbinden. Die mit dem Worker verbundenen Ports sind durch die Eigenschaft ports im {{event("connect")}} Event zugänglich. Anschließend verwenden wir die {{domxref("MessagePort")}} start() Methode um den Port zu starten und verwenden den onmessage Handler um die Nachrichten aus dem Main Thread zu behandeln.

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

Spezifikationen

+ + + + + + + + + + + + + + +
SpezifikationStatusKommentar
{{SpecName('HTML WHATWG', "#sharedworker", "SharedWorker")}}{{Spec2('HTML WHATWG')}}Keine Änderung von {{SpecName("Web Workers")}}.
+ +

Browser Kompatibilität

+ + + +

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

+ +

Siehe auch

+ + diff --git a/files/de/web/api/speechsynthesis/index.html b/files/de/web/api/speechsynthesis/index.html new file mode 100644 index 0000000000..b90f40aa6f --- /dev/null +++ b/files/de/web/api/speechsynthesis/index.html @@ -0,0 +1,134 @@ +--- +title: SpeechSynthesis +slug: Web/API/SpeechSynthesis +translation_of: Web/API/SpeechSynthesis +--- +

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

+ +

Die SpeechSynthesis-Schnittstelle der Web Speech API ist die Controller-Schnittstelle für den Sprachdienst. Sie kann genutzt werden um Informationen über die Synthesestimmen, die auf dem Gerät verfügbar sind, zu erhalten. Außerdem um die Sprache zu starten, zu pausieren und andere Befehle auszuführen.

+ +

Eigenschaften

+ +

SpeechSynthesis erbt ebenfalls Eigenschaften seiner Elternschnittstelle, {{domxref("EventTarget")}}.

+ +
+
{{domxref("SpeechSynthesis.paused")}} {{readonlyinline}}
+
Ein {{domxref("Boolean")}} der true zurückgibt, wenn das SpeechSynthesis-Objekt sich im pausierten Zustand befindet.
+
{{domxref("SpeechSynthesis.pending")}} {{readonlyinline}}
+
Ein {{domxref("Boolean")}} der true zurückgibt, wenn die Äußerungen-Warteschlange bisher ungesprochene Äußerungen enthält.
+
{{domxref("SpeechSynthesis.speaking")}} {{readonlyinline}}
+
Ein {{domxref("Boolean")}} der true zurückgibt, wenn eine Äußerung aktuell gesprochen wird — auch wenn SpeechSynthesis sich aktuell im pausierten Zustand befindet.
+
+ +

Event-Handler

+ +
+
{{domxref("SpeechSynthesis.onvoiceschanged")}}
+
Wird ausgelöst, wenn sich die Liste von {{domxref("SpeechSynthesisVoice")}}-Objekten, die von der {{domxref("SpeechSynthesis.getVoices()")}}-Methode zurückgegeben würde, geändert hat.
+
+ +

Methoden

+ +

SpeechSynthesis erbt ebenfalls Methoden von seiner Elternschnittstelle, {{domxref("EventTarget")}}.

+ +
+
{{domxref("SpeechSynthesis.cancel()")}}
+
Entfernt alle Äußerungen aus der Äußerungen-Warteschlange.
+
{{domxref("SpeechSynthesis.getVoices()")}}
+
Gibt eine Liste von {{domxref("SpeechSynthesisVoice")}}-Objecten zurück die alle verfügbaren Stimmen auf dem aktuellen Gerät repräsentiert.
+
{{domxref("SpeechSynthesis.pause()")}}
+
Versetzt das SpeechSynthesis-Objekt in den pausierten Zustand.
+
{{domxref("SpeechSynthesis.resume()")}}
+
Versetzt das SpeechSynthesis-Object in den nicht-pausierten Zustand: setzt es fort, wenn es bereits pausiert war.
+
{{domxref("SpeechSynthesis.speak()")}}
+
Fügt eine {{domxref("SpeechSynthesisUtterance", "Äußerung")}} Äußerung zur Äußerungen-Warteschlange hinzu; sie wird gesprochen, wenn alle anderen davor eingereihten Äußerungen fertig gesprochen wurden.
+
+ +

Beispiele

+ +

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(),  create a new {{domxref("SpeechSynthesisUtterance")}} instance containing the text from the text {{htmlelement("input")}}, set the utterance's 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('.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();
+}
+ +

Spezifikationen

+ + + + + + + + + + + + + + +
SpezifikationStatusKommentar
{{SpecName('Web Speech API', '#tts-section', 'SpeechSynthesis')}}{{Spec2('Web Speech API')}} 
+ +

Browserkompatibilität

+ +
+ + +

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

+
+ +

Siehe auch

+ + diff --git a/files/de/web/api/storage/clear/index.html b/files/de/web/api/storage/clear/index.html new file mode 100644 index 0000000000..5e6c6d5678 --- /dev/null +++ b/files/de/web/api/storage/clear/index.html @@ -0,0 +1,61 @@ +--- +title: Storage.clear() +slug: Web/API/Storage/clear +tags: + - API Methode Storage +translation_of: Web/API/Storage/clear +--- +

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

+ +

Die Methode clear() der {{domxref("Storage")}}-Schnittstelle löscht sämtliche Datensätze des Objekts.

+ +

Syntax

+ +
storage.clear();
+ +

Rückgabewert

+ +

{{jsxref("undefined")}}.

+ +

Beispiele

+ +

Die folgende Funktion speichert drei Datensätze und löscht sie abschließend mit clear().

+ +
function populateStorage() {
+  localStorage.setItem('bgcolor', 'red');
+  localStorage.setItem('font', 'Helvetica');
+  localStorage.setItem('image', 'miGato.png');
+
+  localStorage.clear();
+}
+ +
+

Hinweis: Weitere Beispiele sind im Web-Storage-Demo zu finden.

+
+ +

Spezifikationen

+ + + + + + + + + + + + + + +
SpezifikationStatusKommentar
{{SpecName('HTML WHATWG', 'webstorage.html#dom-storage-clear', 'Storage.clear')}}{{Spec2('HTML WHATWG')}} 
+ +

Browserkompatibilität

+ + + +

{{Compat("api.Storage.clear")}}

+ +

Siehe auch

+ +

Using the Web Storage API

diff --git a/files/de/web/api/storage/getitem/index.html b/files/de/web/api/storage/getitem/index.html new file mode 100644 index 0000000000..364c3cbc83 --- /dev/null +++ b/files/de/web/api/storage/getitem/index.html @@ -0,0 +1,78 @@ +--- +title: Storage.getItem() +slug: Web/API/Storage/getItem +tags: + - API Methode Storage +translation_of: Web/API/Storage/getItem +--- +

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

+ +

Die Methode getItem() der {{domxref("Storage")}}-Schnittstelle gibt bei Nennung des Schlüssels im Parameter keyName den Wert des zugehörigen Datensatzes zurück.

+ +

Syntax

+ +
var aValue = storage.getItem(keyName);
+
+ +

Parameter

+ +
+
keyName
+
Ein {{domxref("DOMString")}}, der den Namen des Schlüssels, dessen Wert ausgelesen werden soll, enthält.
+
+ +

Rückgabewert

+ +

Ein {{domxref("DOMString")}}, der den Wert des Schlüssels enthält. Falls der Schlüssel nicht existiert, wird null zurückgegeben.

+ +

Beispiel

+ +

Die folgende Funktion liest drei Datenwerte aus dem lokalen Speicher und verwendet sie, um einen benutzerdefinierten Style auf einer Seite zu setzen.

+ +
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);
+}
+ +
+

Hinweis: Weitere Beispiele sind im Web-Storage-Demo zu finden.

+
+ +

Spezifikationen

+ + + + + + + + + + + + + + +
SpezifikationStatusKommentar
{{SpecName('HTML WHATWG', 'webstorage.html#dom-storage-getitem', 'Storage.getItem')}}{{Spec2('HTML WHATWG')}} 
+ +

Browserkompatibilität

+ + + +

{{Compat("api.Storage.getItem")}}

+ +

Siehe auch

+ + diff --git a/files/de/web/api/storage/index.html b/files/de/web/api/storage/index.html new file mode 100644 index 0000000000..7b5d09b041 --- /dev/null +++ b/files/de/web/api/storage/index.html @@ -0,0 +1,161 @@ +--- +title: Storage +slug: Web/API/Storage +translation_of: Web/API/Storage +--- +

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

+ +

Die Storage-Schnittstelle der Web-Storage-API ermöglicht den Zugriff auf einfache Schlüssel-Wert-Datenbanken des Browsers, in denen Daten mit einer Domain verknüpft gespeichert werden können.

+ +

In {{domxref("Window.sessionStorage")}} gespeicherte Daten verfallen mit Ablauf der Sitzung (in der Regel dem Schließen des Browsers), {{domxref("Window.localStorage")}} speichert die Daten hingegen grundsätzlich zeitlich unbegrenzt.

+ +

Eigenschaften

+ +
+
{{domxref("Storage.length")}} {{readonlyInline}}
+
Anzahl der in diesem Storage-Objekt gespeicherten Datensätze.
+
+ +

Methoden

+ +
+
{{domxref("Storage.key()")}}
+
Gibt unter Angabe einer Zahl n den Schlüssel des n-ten Datensatzes zurück.
+
+ +
+
{{domxref("Storage.getItem()")}}
+
Gibt den zum Schlüssel gehörigen Wert zurück.
+
{{domxref("Storage.setItem()")}}
+
Speichert den gegebenen Wert im Storage-Objekt unter dem gegebenen Schlüssel. Ist unter diesem Schlüssel bereits ein Datensatz vorhanden, wird sein Wert mit dem gegebenen überschrieben.
+
{{domxref("Storage.removeItem()")}}
+
Löscht den Datensatz des gegebenen Schlüssels.
+
{{domxref("Storage.clear()")}}
+
Löscht sämtliche Datensätze des Storage-Objekts.
+
+ +

Beispiele

+ +

In diesem Beispiel wird auf das Storage-Objekt localStorage zugegriffen.

+ +

Zuerst wird mit !localStorage.getItem('bgcolor') geprüft, ob das Objekt keinen Datensatz namens bgcolor enthält. Ist der Datensatz bgcolor nicht vorhanden, wird populateStorage() aufgerufen, um Werte aus der Seite auszulesen und mittels {{domxref("Storage.setItem()")}} im Storage-Objekt zu speichern.
+ Anschließend folgt der Aufruf der Funktion setStyles(), die alle Daten mittels {{domxref("Storage.getItem()")}} ausliest und die Darstellung der Seite entsprechend ändert.
+  

+ +
if(!localStorage.getItem('bgcolor')) {
+  populateStorage();
+}
+setStyles();
+
+function populateStorage() {
+  localStorage.setItem('bgcolor', document.getElementById('bgcolor').value);
+  localStorage.setItem('font', document.getElementById('font').value);
+  localStorage.setItem('image', document.getElementById('image').value);
+}
+
+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);
+}
+ +
+

Anmerkung: Dieses Beispiel kann unter Web Storage Demo ausprobiert werden.

+
+ +

Spezifikationen

+ + + + + + + + + + + + + + +
SpezifikationStatusKommentar
{{SpecName('Web Storage', '#the-storage-interface', 'Storage')}}{{Spec2('Web Storage')}} 
+ +

Browserkompatibilität

+ +

{{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 }}8113.2[1]
+
+ +

[1] Seit iOS 5.1 speichert Safari Mobile in localStorage abgelegte Daten im Cache-Verzeichnis. Dieses wird in unregelmäßigen Abständen vom Betriebssystem teilweise geleert, spätestens jedoch, sobald nur noch wenig Speicherplatz zur Verfügung steht.
+ Desweiteren verhindert der private Modus von Safari Mobile jegliche Nutzung von localStorage.

+ +

Die Speicherkapazität von localStorage und sessionStorage. unterscheidet sich von Browser zu Browser (siehe diese detailierte Aufstellung der Speicherkapazitäten für verschiedene Browser).

+ +

Siehe auch

+ +

Using the Web Storage API

diff --git a/files/de/web/api/storage/key/index.html b/files/de/web/api/storage/key/index.html new file mode 100644 index 0000000000..65e56c9ec0 --- /dev/null +++ b/files/de/web/api/storage/key/index.html @@ -0,0 +1,75 @@ +--- +title: Storage.key() +slug: Web/API/Storage/key +tags: + - API Methode Storage +translation_of: Web/API/Storage/key +--- +

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

+ +

Die Methode key() der {{domxref("Storage")}}-Schnittstelle gibt durch Übergabe des Parameters n den Schlüssel des n-ten Datensatzes zurück.
+ Die Reihenfolge der Schlüssel folgt keiner Vorgabe und hängt alleine vom Browser ab.

+ +

Syntax

+ +
var aKeyName = storage.key(index);
+ +

Parameter

+ +
+
index
+
Ein Integer, der die Position des gewünschten Schlüssels bestimmt. Die Nummerierung beginnt bei 0.
+
+ +

Rückgabewert

+ +

Ein {{domxref("DOMString")}} mit dem Namen des Schlüssels.

+ +

Beispiele

+ +

Die folgende Funktion liest in einer Schleife für jeden Datensatz den Schlüssel und übergibt diesen an die Funktion callback():

+ +
function forEachKey(callback) {
+  for (var i = 0; i < localStorage.length; i++) {
+    callback(localStorage.key(i));
+  }
+}
+ +

Nachfolgend wird in einer Schleife zu jedem Datensatz erst der Schlüssel, dann mit dem Schlüssel der Wert gelesen und dieser in der Konsole ausgegeben.

+ +
for (var i = 0; i < localStorage.length; i++) {
+   var key = localStorage.key(i);
+   var value = localStorage.getItem(key);
+   console.log(value);
+}
+ +
+

Hinweis: Weitere Beispiele sind in der Web-Storage-Demo zu finden.

+
+ +

Spezifikationen

+ + + + + + + + + + + + + + +
SpezifikationStatusComment
{{SpecName('HTML WHATWG', 'webstorage.html#dom-storage-key', 'Storage.key')}}{{Spec2('HTML WHATWG')}} 
+ +

Browserkompatibilität

+ + + +

{{Compat("api.Storage.key")}}

+ +

Siehe auch

+ +

Using the Web Storage API

diff --git a/files/de/web/api/storage/length/index.html b/files/de/web/api/storage/length/index.html new file mode 100644 index 0000000000..767ef0c21b --- /dev/null +++ b/files/de/web/api/storage/length/index.html @@ -0,0 +1,63 @@ +--- +title: Storage.length +slug: Web/API/Storage/length +tags: + - API Eigenschaft Storage +translation_of: Web/API/Storage/length +--- +

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

+ +

Die length-Eigenschaft der {{domxref("Storage")}}-Schnittstelle enthält die Anzahl der im Storage-Objekt gespeicherten Datensätze.

+ +

Syntax

+ +
var aLength = Storage.length;
+ +

Rückgabewert

+ +

Ein Integer.

+ +

Beispiel

+ +

Die folgende Funktion fügt drei Datensätze hinzu und liest abschließend die Anzahl der vorhandenen Datensätze:

+ +
function populateStorage() {
+  localStorage.setItem('bgcolor', 'yellow');
+  localStorage.setItem('font', 'Helvetica');
+  localStorage.setItem('image', 'cats.png');
+
+  localStorage.length; // sollte 3 zurückgeben
+}
+ +
+

Hinweis: Weitere Beispiele sind im Web-Storage-Demo zu finden.

+
+ +

Spezifikation

+ + + + + + + + + + + + + + +
SpezifikationStatusKommentar
{{SpecName('HTML WHATWG', 'webstorage.html#dom-storage-length', 'Storage.length')}}{{Spec2('HTML WHATWG')}} 
+ +

Browserkompatibilität

+ + + +

{{Compat("api.Storage.length")}}

+ +

Siehe auch

+ + diff --git a/files/de/web/api/storage/removeitem/index.html b/files/de/web/api/storage/removeitem/index.html new file mode 100644 index 0000000000..6b180f52db --- /dev/null +++ b/files/de/web/api/storage/removeitem/index.html @@ -0,0 +1,68 @@ +--- +title: Storage.removeItem() +slug: Web/API/Storage/removeItem +tags: + - API Methode Storage Speicher +translation_of: Web/API/Storage/removeItem +--- +

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

+ +

Die Methode removeItem() der {{domxref("Storage")}}-Schnittstelle löscht den im Parameter keyName benannten Datensatz aus dem Speicher. Ist kein Datensatz unter diesem Schlüssel vorhanden, tut diese Funktion nichts.

+ +

Syntax

+ +
storage.removeItem(keyName);
+ +

Parameter

+ +
+
keyName
+
Ein {{domxref("DOMString")}}, der den Schlüssel des zu löschenden Datensatzes enthält.
+
+ +

Rückgabewert

+ +

Keiner.

+ +

Beispiel

+ +

Die nachfolgende Funktion speichert drei Datensätze und löscht abschließend den Datensatz mit dem Schlüssel image.

+ +
function populateStorage() {
+  localStorage.setItem('bgcolor', 'red');
+  localStorage.setItem('font', 'Helvetica');
+  localStorage.setItem('image', 'myCat.png');
+
+  localStorage.removeItem('image');
+}
+ +
+

Hinweis: Weitere Beispiele sind im Web-Storage-Demo zu finden.

+
+ +

Spezifikationen

+ + + + + + + + + + + + + + +
SpezifikationStatusKommentar
{{SpecName('HTML WHATWG', 'webstorage.html#dom-storage-removeitem', 'Storage.removeItem')}}{{Spec2('HTML WHATWG')}} 
+ +

Browserkompatibilität

+ + + +

{{Compat("api.Storage.removeItem")}}

+ +

Siehe auch

+ +

Using the Web Storage API

diff --git a/files/de/web/api/storage/setitem/index.html b/files/de/web/api/storage/setitem/index.html new file mode 100644 index 0000000000..94145670a9 --- /dev/null +++ b/files/de/web/api/storage/setitem/index.html @@ -0,0 +1,146 @@ +--- +title: Storage.setItem() +slug: Web/API/Storage/setItem +tags: + - API + - Méthode + - Referenz + - Speicher + - Webspeicher + - localStorage + - sessionStorage +translation_of: Web/API/Storage/setItem +--- +

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

+ +

Die Methode setItem() der {{domxref("Storage")}}-Schnittstelle fügt das gegebene Schlüssel-Wert-Paar zum Speicher hinzu oder überschreibt ein bereits unter diesem Schlüssel im Speicher vorhandenes.

+ +

Syntax

+ +
storage.setItem(keyName, keyValue);
+ +

Parameter

+ +
+
keyName
+
Ein {{domxref("DOMString")}} mit dem Schlüssel des Datensatzes, der erstellt oder überschrieben werden soll.
+
keyValue
+
Ein {{domxref("DOMString")}} mit dem Wert, der in den mit keyName benannten Datensatz geschrieben werden soll.
+
+ +

Rückgabewert

+ +

Keiner.

+ +

Fehler

+ +

setItem() kann bei vollem Speicher eine Exception auslösen. Insbesondere im mobilen Safari (ab iOS 5) wird sie immer ausgelöst, falls der Nutzer sich im privaten Modus befindet, da Safari in diesem Modus das Speicherkontingent auf 0 Bytes setzt. Andere Browser nutzen für den privaten Modus einen separaten Daten-Container.
+ Deshalb sollte immer sichergestellt sein, dass ein möglicher Fehler eingeplant und entsprechend behandelt wird.

+ +

Beispiel

+ +

Die folgende Funktion erstellt drei Datensätze im localStorage-Objekt.

+ +
function populateStorage() {
+  localStorage.setItem('bgcolor', 'red');
+  localStorage.setItem('font', 'Helvetica');
+  localStorage.setItem('image', 'myCat.png');
+}
+ +
+

Hinweis: Weitere Beispiele sind im Web-Storage-Demo zu finden.

+
+ +

Spezifikationen

+ + + + + + + + + + + + + + +
SpezifikationStatusKommentar
{{SpecName('HTML WHATWG', 'webstorage.html#dom-storage-setitem', 'Storage.setItem')}}{{Spec2('HTML WHATWG')}} 
+ +

Browserkompatibilität

+ +

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

Alle Browser haben verschiedene Kapazitäten für localStorage und sessionStorage. Hier gibt es eine detaillierten Übersicht der Kapazitäten verschiedener Browser.

+ +
+

Hinweis: Seit iOS 5.1, speichert Safari Mobile localStorage-Daten im Cache-Ordner, der gelegentlich durch das Betriebssystem geleert wird, insbesondere falls nur noch wenig freier Speicher zur Verfügung steht.

+
+ +

Siehe auch

+ + diff --git a/files/de/web/api/transferable/index.html b/files/de/web/api/transferable/index.html new file mode 100644 index 0000000000..20ed3dfccd --- /dev/null +++ b/files/de/web/api/transferable/index.html @@ -0,0 +1,122 @@ +--- +title: Transferable +slug: Web/API/Transferable +tags: + - API + - Interface + - Reference + - Web Workers + - postMessage +translation_of: Web/API/Transferable +--- +

{{ ApiRef("HTML DOM") }}

+ +

Das Transferable Interface stellt ein Objekt dar, welches zwischen unterschiedlichen Ausführungskontexten, wie zum Beispiel dem main thread und Web Workers, ausgetauscht werden kann.

+ +

Es existiert von dem Interface keine Instanz und kein Objekt. Ebenso definiert es keinerlei Eigenschaften und Methoden. Zweck des Transferable Interface ist lediglich die Möglichkeit der Kennzeichnung von Objekten für die spezifische Situation eines Transfers und Austauschs etwa zwischen Anwendung und {{domxref("Worker")}} via {{domxref("Worker.postMessage()")}}.

+ +

Die Typen {{jsxref("ArrayBuffer")}}, {{domxref("MessagePort")}} and {{domxref("ImageBitmap")}} implementieren dieses Interface.

+ +

Properties

+ +

Das Transferable Interface implementiert und erbt keine spezifischen Eigenschaften.

+ +

Methods

+ +

Das Transferable Interface implementiert und erbt keine spezifischen Methoden.

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "infrastructure.html#transferable-objects", "Transferable")}}{{Spec2('HTML WHATWG')}}Keine Änderung von {{SpecName("HTML5 W3C")}}, wenngleich das neue {{domxref("CanvasProxy")}} auch Transferable implementiert.
{{SpecName('HTML5 W3C', "infrastructure.html#transferable-objects", "Transferable")}}{{Spec2('HTML5 W3C')}}Initiale Definition.
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatVersionUnknown}}{{CompatGeckoDesktop("2.0")}}10.0 [1]{{CompatVersionUnknown}}{{CompatVersionUnknown}}
MessagePort{{CompatUnknown}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatGeckoMobile("2.0")}}10.0 [1]{{CompatVersionUnknown}}{{CompatVersionUnknown}}
MessagePort{{CompatUnknown}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1] Internet Explorer 10 only accepts a single {{domxref("Transferable")}} object as parameter, but not an array.

+ +

See also

+ + diff --git a/files/de/web/api/url/createobjecturl/index.html b/files/de/web/api/url/createobjecturl/index.html new file mode 100644 index 0000000000..f3668e7f70 --- /dev/null +++ b/files/de/web/api/url/createobjecturl/index.html @@ -0,0 +1,139 @@ +--- +title: URL.createObjectURL() +slug: Web/API/URL/createObjectURL +tags: + - API + - Experimentell + - Méthode + - URL + - URL API +translation_of: Web/API/URL/createObjectURL +--- +

{{ApiRef("URL API")}}{{SeeCompatTable}}

+ +

Zusammenfassung

+ +

Die statische Methode URL.createObjectURL() erzeugt einen {{domxref("DOMString")}}, welcher eine URL enthält, die das übergebene Objekt repräsentiert. Die Gültigkeitsdauer der URL ist von dem Dokumentobjekt {{domxref("document")}} abhängig, in dessen Fenster sie erzeugt wurde. Die neue Objekt-URL repräsentiert das angegebene {{domxref("File")}}- bzw. {{domxref("Blob")}}-Objekt.

+ +

Syntax

+ +
objectURL = URL.createObjectURL(blob);
+
+ +

Parameter

+ +
+
blob
+
+ +
+
Ist ein {{domxref("File")}}-Objekt oder ein {{domxref("Blob")}}-Objekt, für das eine URL generiert werden soll.
+
+ + + +

Beispiele

+ +

Siehe "Using object URLs to display images".

+ +

Anmerkungen

+ +

Immer, wenn createObjectURL() aufgerufen wird, wird eine neue Objekt-URL erzeugt, auch wenn schon eine URL für das gleiche Objekt existiert. Jede dieser URLs muss durch einen Aufruf von {{domxref("URL.revokeObjectURL()")}}  wieder freigegeben werden, sofern sie nicht mehr benötigt wird. Wenn das Dokument geschlossen wird, gibt der Browser die URLs automatisch wieder frei. Für eine optimale Performance and Speichernutzung sollten die URLs freigegeben werden, sofern sichergestellt werden kann, dass sie nicht mehr benötigt werden.

+ +

Spezifikationen

+ + + + + + + + + + + + + + +
SpezifikationStatusKommentar
{{SpecName('File API', '#dfn-createObjectURL', 'URL')}}{{Spec2('File API')}}Erste Definition.
+ +

Browserkompatibilität

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Grundlegende Unterstützung8 mit vorangestelltem webkitURL für URL
+ {{CompatChrome(23)}}
{{CompatGeckoDesktop(2)}}{{CompatIE(10)}}{{CompatOpera(15)}}{{CompatSafari(6)}} mit vorangestelltem webkitURL für URL
+ {{CompatSafari(7)}}
In a {{ domxref("Worker", "Web Worker") }}10 mit vorangestelltem webkitURL für URL
+ {{CompatChrome(23)}}
{{CompatGeckoDesktop(21)}}{{CompatIE(11)}}{{CompatOpera(15)}}{{CompatSafari(6)}} mit vorangestelltem webkitURL für URL
+ {{CompatSafari(7)}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChrome for AndroidAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support18 mit vorangestelltem webkitURL für URL4.0 mit vorangestelltem webkitURL für URL{{CompatGeckoMobile(14)}}{{CompatUnknown}}{{CompatOpera(15)}} mit vorangestelltem webkitURL für URL6.0 mit vorangestelltem webkitURL für URL
In einem {{ domxref("Worker", "Web Worker") }}18 mit vorangestelltem webkitURL für URL{{CompatVersionUnknown}} mit vorangestelltem webkitURL für URL{{CompatGeckoMobile(14)}}{{CompatUnknown}}{{CompatOpera(15)}} mit vorangestelltem webkitURL für URL6.0 mit vorangestelltem webkitURL für URL
+
+ +

Siehe auch

+ + diff --git a/files/de/web/api/url/index.html b/files/de/web/api/url/index.html new file mode 100644 index 0000000000..6f1bb53686 --- /dev/null +++ b/files/de/web/api/url/index.html @@ -0,0 +1,222 @@ +--- +title: URL +slug: Web/API/URL +tags: + - API + - Experimental + - NeedsTranslation + - TopicStub + - URL API +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 {{domxref("Window.URL")}} properties (prefixed with Webkit-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

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support8.0 as webkitURL
+ 35
{{CompatGeckoDesktop("2.0")}} (non-standard name) [1]
+ {{CompatGeckoDesktop("19.0")}}
10.015.0 as webkitURL
+ {{CompatVersionUnknown}}
6.0 as webkitURL
+ 7.0
URLUtils properties32{{CompatVersionUnknown}}{{CompatUnknown}}19{{CompatVersionUnknown}}
username, password, and origin32{{CompatGeckoDesktop("26.0")}}{{CompatUnknown}}19{{CompatVersionUnknown}}
protocol, host, hostname, port, href, pathname, search, hash32{{CompatGeckoDesktop("22.0")}}{{CompatUnknown}}19{{CompatVersionUnknown}}
searchParams{{CompatNo}}{{CompatGeckoDesktop("29.0")}}{{CompatUnknown}}19{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}as webkitURL{{CompatGeckoMobile("14.0")}}(non-standard name) [1]
+ {{CompatGeckoMobile("19.0")}}
{{CompatVersionUnknown}}15.0 as webkitURL +

6.0 as webkitURL

+ +

 

+
URLUtils {{CompatUnknown}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}
username, password, href, and origin{{CompatUnknown}}{{CompatGeckoDesktop("26.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}
+
+ +

[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/de/web/api/url/protocol/index.html b/files/de/web/api/url/protocol/index.html new file mode 100644 index 0000000000..08d4ad6b6f --- /dev/null +++ b/files/de/web/api/url/protocol/index.html @@ -0,0 +1,61 @@ +--- +title: URL.protocol +slug: Web/API/URL/protocol +tags: + - API + - Property + - Protocols + - Reference + - URL +translation_of: Web/API/URL/protocol +--- +
{{ApiRef("URL API")}}
+ +

Die protocol Eigenschaft der {{domxref("URL")}} Schnittstelle ist ein {{domxref("USVString")}} der das Protokollschema der URL, einschließlich des finalen ':' darstellt.

+ +

{{AvailableInWorkers}}

+ +

Syntax

+ +
string = object.protocol;
+object.protocol = string;
+
+ +

Wert

+ +

Ein {{domxref("USVString")}}.

+ +

Beispiele

+ +
var url = new URL('https://developer.mozilla.org/en-US/docs/Web/API/URL/protocol');
+var result = url.protocol; // Gibt "https:" zurück.
+
+ +

Spezifikationen

+ + + + + + + + + + + + + + +
SpezifikationStatusKommentar
{{SpecName('URL', '#dom-url-protocol', 'protocol')}}{{Spec2('URL')}}Erste Definition.
+ +

Browserkompatibilität

+ + + +

{{Compat("api.URL.protocol")}}

+ +

Siehe auch

+ + diff --git a/files/de/web/api/urlsearchparams/index.html b/files/de/web/api/urlsearchparams/index.html new file mode 100644 index 0000000000..3c635d180d --- /dev/null +++ b/files/de/web/api/urlsearchparams/index.html @@ -0,0 +1,211 @@ +--- +title: URLSearchParams +slug: Web/API/URLSearchParams +tags: + - API + - Experimentell + - Interface + - Referenz + - URL API +translation_of: Web/API/URLSearchParams +--- +

{{ApiRef("URL API")}}

+ +

Das URLSearchParams Interface definiert Hilfsmethoden um mit dem Query-String einer URL zu arbeiten.

+ +

Ein Objekt, welches URLSearchParams implementiert, kann auch direkt in einem {{jsxref("Statements/for...of", "for...of")}} Konstrukt genutzt werden, anstatt {{domxref('URLSearchParams.entries()', 'entries()')}}: for (var p of mySearchParams) ist äquivalent zu for (var p of mySearchParams.entries()).

+ +

Konstruktor

+ +
+
{{domxref("URLSearchParams.URLSearchParams", 'URLSearchParams()')}}
+
Konstruktor erzeugt ein URLSearchParams Objekt von einem Query-String.
+
+ +

Eigenschaften

+ +

Dieses Interface erbt keine Eigenschaften.

+ +

Methoden

+ +

Dieses Interface erbt keine Methoden.

+ +
+
{{domxref("URLSearchParams.append()")}}
+
Hängt ein Schlüssel/Wert - Paar an den Query-String.
+
{{domxref("URLSearchParams.delete()")}}
+
Löscht einen Schlüssel und den zugehörigen Wert aus dem Query-String.
+
{{domxref("URLSearchParams.entries()")}}
+
Gibt einen {{jsxref("Iteration_protocols","Iterator")}} über alle Schlüssel/Wert - Paare im Query-String.
+
{{domxref("URLSearchParams.get()")}}
+
Gibt den ersten Wert, der im Query-String mit einem Schlüssel assoziiert ist.
+
{{domxref("URLSearchParams.getAll()")}}
+
Gibt alle Werte, die im Query-String mit einem Schlüssel assoziiert sind.
+
{{domxref("URLSearchParams.has()")}}
+
Gibt einen {{jsxref("Boolean")}}, der anzeigt ob ein Schlüssel im Query-String vorkommt.
+
{{domxref("URLSearchParams.keys()")}}
+
Gibt einen {{jsxref("Iteration_protocols", "Iterator")}} über alle Schlüssel im Query-String.
+
{{domxref("URLSearchParams.set()")}}
+
Setzt den Wert eines Schlüssels. Wenn der Schlüssel mehrfach im Query-String vorkommt, werden die Restlichen gelöscht.
+
{{domxref("URLSearchParams.sort()")}}
+
Sortiert alle Schlüssel/Wert Paare, nach dem Schlüssel.
+
Sorts all key/value pairs, if any, by their keys.
+
{{domxref("URLSearchParams.toString()")}}
+
Gibt den Query-String, in der passenden Form um in einer URL einzusetzen.
+
{{domxref("URLSearchParams.values()")}}
+
Gibt einen {{jsxref("Iteration_protocols", "Iterator")}} über alle Werte im Query-String.
+
+ +

Beispiel

+ +
var paramsString = "q=URLUtils.searchParams&topic=api"
+var searchParams = new URLSearchParams(paramsString);
+
+//Iteriert über die Suchparameter
+for (let p of searchParams) {
+  console.log(p);
+}
+
+searchParams.has("topic") === true; // true
+searchParams.get("topic") === "api"; // true
+searchParams.getAll("topic"); // ["api"]
+searchParams.get("foo") === null; // true
+searchParams.append("topic", "webdev");
+searchParams.toString(); // "q=URLUtils.searchParams&topic=api&topic=webdev"
+searchParams.set("topic", "More webdev");
+searchParams.toString(); // "q=URLUtils.searchParams&topic=More+webdev"
+searchParams.delete("topic");
+searchParams.toString(); // "q=URLUtils.searchParams"
+
+ +

Spezifikationen

+ + + + + + + + + + + + + + + + +
SpezifikationStatusKommentar
{{SpecName('URL', '#urlsearchparams', "URLSearchParams")}}{{Spec2('URL')}}Initial definition.
+ +

Browser Kompatibilität

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome(49)}}{{CompatGeckoDesktop("29.0")}}{{CompatNo}}3610.1
entries(), keys(), values(), and support of for...of{{CompatChrome(49)}}{{CompatGeckoDesktop("44.0")}}{{CompatNo}}36{{CompatUnknown}}
USVString for constructor init object{{CompatVersionUnknown}}{{CompatGeckoDesktop("53.0")}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatUnknown}}
Record for constructor init object{{CompatNo}}{{CompatGeckoDesktop("54.0")}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroid WebviewChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatChrome(49)}}{{CompatChrome(49)}}{{CompatGeckoMobile("29.0")}}{{CompatNo}}{{CompatUnknown}}{{CompatNo}}
entries(), keys(), values(), and support of for...of{{CompatChrome(49)}}{{CompatChrome(49)}}{{CompatGeckoMobile("44.0")}}{{CompatNo}}{{CompatUnknown}}{{CompatNo}}
USVString for constructor init object{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("53.0")}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}
Record for constructor init object{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile("54.0")}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

Verweise

+ + + +
+
diff --git a/files/de/web/api/usvstring/index.html b/files/de/web/api/usvstring/index.html new file mode 100644 index 0000000000..4021cc4cc8 --- /dev/null +++ b/files/de/web/api/usvstring/index.html @@ -0,0 +1,42 @@ +--- +title: USVString +slug: Web/API/USVString +tags: + - API + - DOM + - DOM Referenz + - Referenz + - String + - WebIDL +translation_of: Web/API/USVString +--- +

{{APIRef("DOM")}}

+ +

Ein USVString entspricht der Menge aller möglichen Folgen von Unicode-Skalarwerten. USVString konvertiert zu String, wenn es in JavaScript zurückgegeben wird; Es wird allgemein nur für APIs verwendet, die Text verarbeiten und einen String mit Unicode-Skalarwerten benötigen. USVString ist gleich zu DOMString, mit der Ausnahme, dass USVString ungepaarte Ersatzcodepoints nicht erlaubt. Ungepaarte Ersatzcodepoints in einem USVString werden vom Browser zum Unicode 'Ersatzzeichen' U+FFFD konvertiert.

+ +

Spezifikationen

+ + + + + + + + + + + + + + +
SpezifikationStatusKommentar
{{SpecName('WebIDL', '#idl-USVString', 'USVString')}}{{Spec2('WebIDL')}}Initiale Definition.
+ +

Siehe auch

+ + diff --git a/files/de/web/api/vollbild_api/index.html b/files/de/web/api/vollbild_api/index.html new file mode 100644 index 0000000000..1ddce4c572 --- /dev/null +++ b/files/de/web/api/vollbild_api/index.html @@ -0,0 +1,305 @@ +--- +title: Vollbild API +slug: Web/API/Vollbild_API +tags: + - API + - DOM + - JS + - Tutorial + - Vollbild API +translation_of: Web/API/Fullscreen_API +--- +

{{DefaultAPISidebar("Fullscreen API")}}

+ +

Die Vollbild-API bietet einen einfachen Weg, um Webinhalte auf dem gesamten Bildschirm des Nutzers anzuzeigen. Der Browser kann einfach angewiesen werden, Elemente und, falls vorhanden, deren Kinder den gesamten Bildschirm einnehmen zu lassen, wodurch jegliche andere Inhalte vorübergehend ausgeblendet werden.

+ +
+

Momentan benutzen nicht alle Browser die Version der API ohne Präfixe. Siehe Vendor Präfixe für Unterschiede zwischen Präfixen und Namen. 

+ +

Für eine universelle Lösung des Problems siehe Fscreen.

+
+ +

Aktivieren des Vollbildmodus

+ +

Wenn sie ein Element gefunden haben, welches Sie im Vollbildmodus anzeigen möchten (etwa ein {{ HTMLElement("video") }}), wir der Vollbildmodus einfach durch den Aufruf der {{ domxref("Element.requestFullscreen()") }}-Methode gestartet.

+ +

Nehmen wir dieses {{ HTMLElement("video") }}-Element als Beispiel:

+ +
<video controls id="myvideo">
+  <source src="somevideo.webm"></source>
+  <source src="somevideo.mp4"></source>
+</video>
+
+ +

Wir können dieses Video mit folgendem Skript in den Vollbildmodus versetzen:

+ +
var elem = document.getElementById("myvideo");
+if (elem.requestFullscreen) {
+  elem.requestFullscreen();
+}
+
+ +

Anzeige-Schwierigkeiten

+ +

An dieser Stelle lohnt es sich, einen wichtigen Unterschied zwischen Gecko und WebKit aufzuzeigen: Gecko fügt automatisch CSS-Regeln zum betroffenen Element hinzu, damit es den ganzen Bildschirm einnimmt: "width: 100%; height: 100%". WebKit tut dies allerdings nicht; stattdessen wird das Vollbild-Element in der selben Größe zentriert vor einem schwarzen Hintergrund dargestellt. Um das gleich Vollbild-Verhalten in WebKit zu erhalten, müssen Sie selbst eine "width: 100%; height: 100%;"-CSS-Regel zum entsprechenden Element hinzufügen:

+ +
#myvideo:-webkit-full-screen {
+  width: 100%;
+  height: 100%;
+}
+
+ +

Andererseits, wenn Sie stattdessen versuchen, das WebKit-Verhalten auf Gecko zu erreichen, müssen sie das Element, das präsentiert werden soll, in einem anderen Element platzieren, welches sie stattdessen in den Vollbild-Modus versetzen. Dann können sie CSS-Regeln verwenden, um das innere Element so zu layouten, wie Sie wünschen.

+ +

Benachrichtigung

+ +

Wenn der Vollbild-Modus erfolgreich gestartet wird, erhält das document, welches das entsprechende Element enthält ein {{ event("fullscreenchange") }}-Event. Wenn der Vollbild-Modus wieder verlassen wird, erhält das document wiederum ein {{ event("fullscreenchange") }}-Event. Beachten Sie jedoch, dass das {{ event("fullscreenchange") }}-Event selbst keine Informationen darüber bereitstellt, ob das document in oder aus den Vollbild-Modus wechselt. Stattdessen muss überprüft werden, ob das Attribut {{ domxref("document.fullscreenElement", "fullscreenElement") }}, des document nicht null ist. In diesem Fall befindet sich der Browser im Vollbild-Modus.

+ +

Wenn die Vollbild-Anfrage scheitert

+ +

Es ist nicht garantiert, dass der Wechsel in den Vollbild-Modus möglich ist. {{ HTMLElement("iframe") }}-Elements etwa haben das {{ HTMLAttrXRef("allowfullscreen", "iframe") }}-Attribut, um ihrem Inhalt zu erlauben, in den Vollbild-Modus zu wechseln. Zusätzlich gibt es bestimmte Arten von Inhalten, wie etwa windowed plug-ins, welche nicht im Vollbild-Modus angezeigt werden können. Wenn versucht wird, ein Element, welches nicht im Vollbild-Modus dargestellt werden kann (oder ein Eltern- bzw. Kind-Knoten eines solchen Elements), wird dies nicht funktionieren. Stattdessen wird das Element, welches den Vollbild-Modus angefragt hat, ein mozfullscreenerror-Event erhalten. Wenn eine Vollbild-Anfrage scheitert, wird Firefox eine Fehlermeldung auf der Web-Konsole ausgeben, welche erklärt, warum die Anfrage fehlgeschlagen ist. In Chrome und neueren Versionen von Opera werden allerdings keine solchen Warnungen produziert.

+ +
+

Hinweis: Vollbild-Anfragen müssen aus einem Event-Handler heraus gestellt werden oder die Anfrage wird abgelehnt. 

+
+ +

Verlassen des Vollbildmodus

+ +

Der Nutzer hat immer die Möglichkeit, selbst den Vollbildmodus zu verlassen; siehe {{ anch("Things your users want to know") }}. Der Vollbildmodus kann aber auch programmatisch mithilfe der  {{domxref("Document.exitFullscreen()")}}-Methode beendet werden.

+ +

Weitere Informationen

+ +

Das {{ domxref("document") }} hält weitere Informationen bereit, welche bei der Entwicklung von Vollbild-Web-Apps hilfreich sein können:

+ +
+
{{ domxref("document.fullscreenElement", "fullscreenElement") }}
+
Das fullscreenElement-Attribut gibt das {{ domxref("element") }} an, welches aktuell im Vollbild-Modus angezeigt wird. Wenn dies nicht null ist, befindet sich das document im Vollbildmodus. Sonst, wenn dieses Attribut null ist, befindet sich das Dokument nicht im Vollbildmodus.
+
{{ domxref("document.fullscreenEnabled", "fullscreenEnabled") }}
+
Das fullscreenEnabled-Attribut gibt an, ob das document aktuell in einem Zustand ist, in welchem der Vollbild-Modus erlaubt ist.
+
+ +

Was die Nutzer wissen wollen

+ +

Sie sollten die Nutzer wissen lassen, dass sie den Vollbildmodus jederzeit mit ESC (oder F11) verlassen können.

+ +

Zusätzlich beendet das Navigieren zu einer anderen Seite oder das Wechseln von Tabs oder Programmen (etwa mit  Alt+Tab) auch den Vollbildmodus.

+ +

Beispiel

+ +

In diesem Beispiel wird ein Video auf einer Webseite dargestellt. Durch drücken von Return oder Enter kann der Nutzer den Vollbildmodus des Videos umschalten.

+ +

Live-Beispiel ansehen

+ +

Watching for the Enter key

+ +

When the page is loaded, this code is run to set up an event listener to watch for the Enter key.

+ +
document.addEventListener("keydown", function(e) {
+  if (e.keyCode == 13) {
+    toggleFullScreen();
+  }
+}, false);
+
+ +

Toggling fullscreen mode

+ +

This code is called when the user hits the Enter key, as seen above.

+ +
function toggleFullScreen() {
+  if (!document.fullscreenElement) {
+      document.documentElement.requestFullscreen();
+  } else {
+    if (document.exitFullscreen) {
+      document.exitFullscreen();
+    }
+  }
+}
+
+ +

This starts by looking at the value of the fullscreenElement attribute on the {{ domxref("document") }} (checking it prefixed with both moz, ms, or webkit). If it's null, the document is currently in windowed mode, so we need to switch to fullscreen mode. Switching to fullscreen mode is done by calling {{ domxref("element.requestFullscreen()") }}.

+ +

If fullscreen mode is already active (fullscreenElement is non-null), we call {{ domxref("document.exitFullscreen()") }}.

+ +

Vendor Präfixe

+ +

For the moment not all browsers are implementing the unprefixed version of the API (for vendor agnostic access to the Fullscreen API you can use Fscreen). Here is the table summarizing the prefixes and name differences between them:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
StandardBlink (Chrome & Opera)Gecko (Firefox)Internet Explorer 11EdgeSafari (WebKit)
{{domxref("Document.fullscreen")}}webkitIsFullScreenmozFullScreen-webkitIsFullScreenwebkitIsFullScreen
{{domxref("Document.fullscreenEnabled")}}webkitFullscreenEnabledmozFullScreenEnabledmsFullscreenEnabledwebkitFullscreenEnabledwebkitFullscreenEnabled
{{domxref("Document.fullscreenElement")}}webkitFullscreenElementmozFullScreenElementmsFullscreenElementwebkitFullscreenElementwebkitFullscreenElement
{{domxref("Document.onfullscreenchange")}}onwebkitfullscreenchangeonmozfullscreenchangeMSFullscreenChangeonwebkitfullscreenchangeonwebkitfullscreenchange
{{domxref("Document.onfullscreenerror")}}onwebkitfullscreenerroronmozfullscreenerrorMSFullscreenErroronwebkitfullscreenerroronwebkitfullscreenerror
{{domxref("Document.exitFullscreen()")}}webkitExitFullscreen()mozCancelFullScreen()msExitFullscreen()webkitExitFullscreen()webkitExitFullscreen()
{{domxref("Element.requestFullscreen()")}}webkitRequestFullscreen()mozRequestFullScreen()msRequestFullscreen()webkitRequestFullscreen()webkitRequestFullscreen()
+ +

Spezifikationen

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("Fullscreen")}}{{Spec2("Fullscreen")}}Initial version.
+ +

Browser Kompatibilität

+ +

All browsers implement this APIs. Nevertheless some implement it with prefixed names with slightly different spelling; e.g., instead of requestFullscreen(), there is MozRequestFullScreen().

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support15 {{ property_prefix("-webkit") }}{{CompatVersionUnknown}}{{ CompatGeckoDesktop("9.0") }} {{ property_prefix("-moz") }}
+ {{CompatGeckoDesktop("47")}} (behind full-screen-api.unprefix.enabled)
11 {{ property_prefix("-ms") }}12.105.0 {{ property_prefix("-webkit") }}
fullscreenEnabled20 {{ property_prefix("-webkit") }}{{CompatVersionUnknown}}{{ CompatGeckoDesktop("10.0") }} {{ property_prefix("-moz") }}
+ {{CompatGeckoDesktop("47")}} (behind full-screen-api.unprefix.enabled)
11 {{ property_prefix("-ms") }}12.105.1 {{ property_prefix("-webkit") }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChromeEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{ CompatUnknown() }}28 {{ property_prefix("-webkit") }}{{CompatVersionUnknown}}{{ CompatGeckoMobile("9.0") }}{{ property_prefix("-moz") }}
+ {{CompatGeckoMobile("47")}} (behind full-screen-api.unprefix.enabled)
{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
fullscreenEnabled{{ CompatUnknown() }}28 {{ property_prefix("-webkit") }}{{CompatVersionUnknown}}{{ CompatGeckoMobile("10.0") }} {{ property_prefix("moz") }}
+ {{CompatGeckoMobile("47")}} (behind full-screen-api.unprefix.enabled)
{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +

Siehe auch

+ + diff --git a/files/de/web/api/web_animations_api/index.html b/files/de/web/api/web_animations_api/index.html new file mode 100644 index 0000000000..ad88873dfd --- /dev/null +++ b/files/de/web/api/web_animations_api/index.html @@ -0,0 +1,99 @@ +--- +title: Web Animations API +slug: Web/API/Web_Animations_API +translation_of: Web/API/Web_Animations_API +--- +

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

+ +
+

Die Web Animations API ermöglicht die Synchronisierung und zeitliche Abstimmung von Änderungen an der Präsentation einer Webseite, d. H. der Animation von DOM-Elementen. Dabei werden zwei Modelle kombiniert: das Timing-Modell und das Animationsmodell.

+
+ +

Konzepte und Verwendung

+ +

Die Web-Animations-API bietet Browsern und Entwicklern eine gemeinsame Sprache, um Animationen auf DOM-Elementen zu beschreiben. Weitere Informationen zu den Konzepten der API und ihrer Verwendung finden Sie unter Verwenden der Web Animations-API.

+ +

Webanimationsschnittstellen

+ +
+
+ +
+
{{domxref("Animation")}}
+
Bietet Steuerelemente zur Wiedergabe und eine Zeitleiste für einen Animationsknoten. Kann ein mit dem {{domxref("KeyframeEffect.KeyframeEffect", "KeyframeEffect()")}} Konstruktor erstelltes Object aufnehmen.
+
{{domxref("KeyframeEffect")}}
+
Beschreibt eine Menge animierbarer Eigenschaften und Werte, die als Keyframes bezeichnet werden, sowie deren Timing-Optionen. Diese können dann mit dem {{domxref("Animation.Animation", "Animation()")}} Konstruktor abgespielt werden. 
+
{{domxref("AnimationTimeline")}}
+
Repräsentiert die Zeitleiste der Animation. Diese Schnittstelle ist zum Definieren von Timeline-Features (geerbt von {{domxref ("DocumentTimeline")}} und zukünftigen Timeline-Objekten) vorhanden, auf die Entwickler nicht selbst zugreifen.
+
{{domxref("AnimationEvent")}}
+
Eigentlich Teil von CSS-Animationen.
+
{{domxref("DocumentTimeline")}}
+
Stellt Animationszeitleisten dar, einschließlich der Standarddokumentzeitleiste (auf die über die Eigenschaft {{domxref ("Document.timeline")}} zugegriffen wird).
+
{{domxref("EffectTiming")}}
+
{{domxref ("Element.animate ()")}}, {{domxref ("KeyframeEffectReadOnly.KeyframeEffectReadOnly ()")}} und {{domxref ("KeyframeEffect.KeyframeEffect ()")}} akzeptieren alle ein optionales Objekt von Timing-Eigenschaften.
+
+ +

Erweiterungen zu anderen Schnittstellen

+ +

 

+ +

Die Web-Animations-API fügt {{domxref ("document")}} und {{domxref ("element")}} einige neue Funktionen hinzu.

+ +

Etweiterungen der Document Schnittstelle

+ +
+
{{domxref("document.timeline")}}
+
Das DocumentTimeline Objekt stellt die Standardzeitleiste des Dokuments dar.
+
{{domxref("document.getAnimations()")}}
+
Gibt ein Array von {{domxref ("Animation")}} - Objekten zurück, die derzeit für Elemente im document wirksam sind.
+
+

Erweiterungen der Element Schnittstelle

+
+
{{domxref("Element.animate()")}}
+
Eine Shortcut-Methode zum Erstellen und Wiedergeben einer Animation für ein Element. Sie gibt die erstellte {{domxref ("Animation")}} Objektinstanz zurück.
+
+ +
+
+ +

Read-Only-Schnittstellen für Web-Animationen

+ +

Die folgenden Schnittstellen sind in der Spezifikation enthalten, z. B. um Features zu definieren, die an mehreren anderen Stellen verwendet werden, oder um als Basis für mehrere Schnittstellen zu dienen, die alle als Werte derselben Eigenschaften verwendet werden können. Du würdest diese nicht direkt in der Entwicklungsarbeit verwenden, aber für Bibliotheksautoren könnte es interessant sein, die Funktionsweise der Technologie zu verstehen, sodass ihre Implementierungen effektiver sein können, oder für Browseringenieure, die eine einfachere Referenz suchen, als die Spezifikation bietet.

+ +
+
{{domxref("AnimationEffectTimingReadOnly")}}
+
Ein dictionary Objekt mit Timing-Eigenschaften, die von der veränderlichen {{domxref ("AnimationEffectTiming")}} - Schnittstelle geerbt werden, die der {{domxref ("KeyframeEffect")}} zugeordnet ist.
+
{{domxref("AnimationEffectReadOnly")}}
+
Defines current and future "Animation Effects" like {{domxref("KeyframeEffect")}}, which can be passed to {{domxref("Animation")}} objects for playing, and {{domxref("KeyframeEffectReadOnly")}} which is used by {{domxref("KeyframeEffect")}} (inherited by CSS Animations and Transitions). All values of {{domxref("Animation.effect")}} are of types based on AnimationEffectReadOnly.
+
{{domxref("KeyframeEffectReadOnly")}}
+
Describes sets of animatable properties and values that can be played using the {{domxref("Animation.Animation", "Animation()")}} constructor, and which are inherited by {{domxref("KeyframeEffect")}}. 
+
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Animations')}}{{Spec2('Web Animations')}}Initial definition
+ +

See also

+ + diff --git a/files/de/web/api/web_storage_api/index.html b/files/de/web/api/web_storage_api/index.html new file mode 100644 index 0000000000..ae3779f420 --- /dev/null +++ b/files/de/web/api/web_storage_api/index.html @@ -0,0 +1,142 @@ +--- +title: Web Storage API +slug: Web/API/Web_Storage_API +translation_of: Web/API/Web_Storage_API +--- +

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

+ +

Die Web Storage API bietet Mechanismen, durch welche Browser in einer weitaus intuitiveren Form Schlüssel-Werte-Paare abspeichern können, als dies bei Cookies der Fall ist.

+ +

Web Storage Konzepte und Verwendung

+ +

Die zwei Mechanismen innerhalb des Web Storage sind wie folgt:

+ + + +

Diese Mechanismen stehen durch die Eigenschaften {{domxref("Window.sessionStorage")}} und {{domxref("Window.localStorage")}} zur Verfügung (um dies näher zu beschreiben: Zur Unterstützung der Browser implementiert das Window Objekt die Objekte WindowLocalStorage und WindowSessionStorage, welche von localStorage und sessionStorage bereitgestellt werden) — durch deren Aufruf wird eine Instanz des {{domxref("Storage")}} Objekts erstellt, durch welches Daten gespeichert, abgerufen und gelöscht werden können. Ein anderes Speicherelement wird für das sessionStorage und localStorage jedes Ausgangspunktes verwendet — beide arbeiten getrennt und werden auch getrennt gesteuert.

+ +
+

Hinweis: Ab Firefox 45 aufwärts wird die Datenspeicherung pro Ausgangspunkt auf 10MB begrenzt, um Speicherprobleme durch übermäßige Verwendung des Web storage zu vermeiden.

+
+ +
+

Hinweis: Zugang zum Web Storage von IFrames Ditter wird verweigert, wenn der Anwender Cookies Dritter deaktiviert hat (Firefox implementiert dieses Verhalten ab der version 43 aufwärts.)

+
+ +
+

Hinweis: Web Storage ist nicht dasselbe wie mozStorage (Mozillas XPCOM Schnittstelle zu SQLite) oder die Session store API (ein XPCOM Speicherprogramm, welches von Erweiterungen verwendet wird).

+
+ +

Web Storage Schnittstellen

+ +
+
{{domxref("Storage")}}
+
Erlaubt das Speichern, Abrufen und Löschen von Daten einer spezifischen Domain und des Speichertyps (session oder local).
+
{{domxref("Window")}}
+
Die Web Storage API erweitert das {{domxref("Window")}} Objekt mit zwei neuen Attributen — {{domxref("Window.sessionStorage")}} und {{domxref("Window.localStorage")}} — welche den Zugang zu den jeweiligen session- und local-Objekten der aktuellen Domain sowie eine {{domxref("Window.onstorage")}} Ereignissteuerung (event handler), welche aktiviert wird, wenn ein Speicherbereich geändert wird (z.B. bei der Speicherung eines neuen Datensatzes).
+
{{domxref("StorageEvent")}}
+
Das storage-Ereignis wird über das Window-Objekt eines (html-) Dokuments aktiviert, wenn sich ein Speicherbereich ändert.
+
+ +

Beispiele

+ +

Um einige der typischen Anwendungsfälle von Web Storage darzulegen, wurde ein einfaches Beispiel erstellt, fantasievoll als Web Storage Demo benannt. Die Startseite bietet die Möglichkeit, Farbe, Schriftart und ein dekoratives Bild zu verändern. Wenn verschiedene Optionen ausgewählt werden, wird die Seite umgehend aktualisiert. Zudem werden die ausgewählten Optionen im localStorage gespeichert, sodass diese beim Verlassen und erneutem Aufruf der Seite bestehen bleiben. 

+ +

Zudem besteht eine Ereignis-Ausgabeseite — wenn diese Seite in einem weiteren Tab geladen wird, hiernach Änderungen auf der Startseite vorgenommen werden, sind die aktualisierten Speicherinformationen zu sehen, welche durch die Aktivierung des Ereignisses {{event("StorageEvent")}} zustandekommen.

+ +

Spezifikationen

+ + + + + + + + + + + + + + +
SpezifikationStatusKommentar
{{SpecName('Web Storage')}}{{Spec2('Web Storage')}}
+ +

Browser-Kompatibilität

+ +

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

Alle Browser haben variiernde Kapazitäten sowohl für das localStorage und auch das sessionStorage. Hier ist ein detailierter Ablauf aller Speicherkapazitäten verschiedener Browser zu finden.

+ +
+

Hinweis: Seit iOS 5.1, speichert Safari Mobile localStorage-Daten in den cache-Ordner, welcher gelegentlichen Speicherbereinigungen durch das OS ausgesetzt ist, welche typischerweise bei knappem Speicher auftreten.

+
+ +

Privates Surfen / Inkognito-Modus

+ +

Die meisten modernen Browser unterstützen die als "Inkognito", "Privates Surfen" o.ä. bezeichnete Datenschutz-Option, welche keine Daten wie Verlauf und Cookies speichert. Aus ersichtlichen Gründen ist dies grundsätzlich inkompatibel mit Web Storage. Nichtsdestotrotz experimentieren Browseranbieter mit verschiedenen Szenarien, um mit dieser Inkompatibilität umzugehen.

+ +

Für die meisten Browser hat man sich für eine Strategie entschieden, wobei Speicher-APIs vorhanden und scheinbar voll funktionsfähig sind, mit dem einen großen Unterschied, dass alle gespeicherten Daten gelöscht werden, nachdem der Browser geschlossen wird. Für diese Browser bestehen desweiteren unterschiedliche Interpretationen dazu, was mit den vorhandenen abgespeicherten Daten (aus einer regulären Sitzung) geschehen soll. Sollten sie zum Abruf zur Verfügung stehen, um im Inkognito-Modus gelesen werden zu können? Dann gibt es einige Browser, insbesondere Safari, welche sich dazu entschieden haben, den Speicher zur Verfügung zu stellen, dieser jedoch leer ist und ihm ein Speicheranteil von 0 Byte zugeordnet ist. Dadurch machen sie es praktisch unmöglich, Daten auf den Speicher zu schreiben.

+ +

Entwicklern sollten diese unterschiedlichen Implementierungen bewusst sein und sie sollten dies bei der Entwicklung von Webseiten, welche von den Web Storage APIs abhängen, in Betracht ziehen. Für weitere Informationen werfe man einen Blick auf diesen WHATWG Blogpost , das sich insbesondere mit diesem Thema befasst.

+ +

Siehe auch

+ +

Using the Web Storage API
+ HTML5 Storage API By Venkatraman

diff --git a/files/de/web/api/web_workers_api/index.html b/files/de/web/api/web_workers_api/index.html new file mode 100644 index 0000000000..46dccd115d --- /dev/null +++ b/files/de/web/api/web_workers_api/index.html @@ -0,0 +1,226 @@ +--- +title: Web Worker API +slug: Web/API/Web_Workers_API +translation_of: Web/API/Web_Workers_API +--- +

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

+ +

Web Workers ermöglichen Entwicklern Skripte in einem Hintergrundthread getrennt vom Haupthread auszuführen. Dies hat den Vorteil, dass rechenintensive Operationen in einem gesonderten Thread ausgeführt werden können und somit der Hauptthread, der für gewöhnlich das UI bereitstellt, arbeiten kann ohne verlangsamt oder blockiert zu werden.

+ +

Web Workers Konzepte und Anwendung

+ +

Ein Worker ist ein Objekt das mit einem Konstruktor erzeugt wird (beispielsweise {{domxref("Worker.Worker", "Worker()")}}) und eine JavaScript Datei mit Namen ausführt. In dieser Datei ist der Code enthalten der im Worker-Thread ausgeführt wird. Worker arbeiten in einem eigenen globalen Kontext, der vom aktuellen Hauptkontext {{domxref("window")}} verschieden ist. Dieser Kontext ist durch das Objekt  {{domxref("DedicatedWorkerGlobalScope")}}  repräsentiert, falls es sich um einen dedizierten Worker handelt (also einen Worker der nur von einem Skript genutzt wird, was der Standard ist.). Shared Workers benutzen das Objekt {{domxref("SharedWorkerGlobalScope")}}.

+ +

Man kann bis auf einige Ausnahmen beliebige Anweisungen ausführen. Beispielsweise kann man das DOM nicht direkt ändern und auch einige Standardmethoden und -attribute von {{domxref("window")}} können nicht genutzt werden. Viele andere Elemente von window können allerdings schon genutzt werden, unter anderem WebSockets und Datenspeicher, wie IndexedDB und die Firefox-OS-only Data Store API.  Unter Functions and classes available to workers finden Sie mehr Details.

+ +

Daten werden zwischen den Workern und dem Hauptthread mithilfe eines Nachrichtensystems verschickt — beide Seiten verschicken ihre Nachrichten mit der postMessage() Methode und antworten mit dem onmessage Event Handler (die empfangene Nachricht ist im data Attribut {{event("Message")}} des Events enthalten). Die Daten werden kopiert und nicht geteilt.

+ +

Worker können neue Worker erzeugen, solange diese vom selben Ursprung gehosted werden wie die Ursprungsseite.  Außerdem können Worker XMLHttpRequest für Netzwerk I/O benutzen mit der Ausnahme, dass  die responseXML und channel Attribute von XMLHttpRequest stets null zurückgeben.

+ +

Neben dedizierten Workern gibt es noch andere Typen:

+ + + +
+

Note: As per the Web workers Spec, worker error events should not bubble (see {{bug(1188141)}}. This has been implemented in Firefox 42.

+
+ +

Web Worker interfaces

+ +
+
{{domxref("AbstractWorker")}}
+
Abstrakte Attribute und Methoden für alle Worker (z.B. {{domxref("Worker")}} oder {{domxref("SharedWorker")}}).
+
{{domxref("Worker")}}
+
Repräsentiert einen laufenden Workerthread. Erlaubt das Senden von Nachrichten an den Code im Worker.
+
{{domxref("WorkerLocation")}}
+
Definiert die absolute Quelle des Skripts das im  Worker ausgeführet wird.
+
+ +
+
{{domxref("SharedWorker")}}
+
Repräsentiert einen speziellen Worker, auf den von verschiedenen Fenstern, IFrames oder sogar Workern  zugegrifffen werden kann.
+
{{domxref("WorkerGlobalScope")}}
+
Repräsentiert den generischen Scope jedes Workers (dies entspricht dem {{domxref("Window")}} objekt für normale Webinhalte). Andere Worker haben Scopes die von diesem vererbt werden und spezifische Eigenschaften hinzufügen.
+
{{domxref("DedicatedWorkerGlobalScope")}}
+
Repräsentiert den von {{domxref("WorkerGlobalScope")}} vererbten Scope eines dedizierten Workers. Fügt besondere Eigenschaften hinzu.
+
{{domxref("SharedWorkerGlobalScope")}}
+
Repräsentiert den von {{domxref("WorkerGlobalScope")}} vererbten Scope eines  Shared Workers. Fügt besondere Eigenschaften hinzu.
+
{{domxref("WorkerNavigator")}}
+
Repräsentiert die Identität und den Zustand des User Agents (dem client).
+
+ +

Beispiele

+ +

Sie finden ein paar einfache Beispiele, die die Benutzung veranschaulichen unter diesen Links:

+ + + +

Unter Using web workers finden Sie mehr Informationen wie diese Demos funktionieren.

+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#workers')}}{{Spec2('HTML WHATWG')}}
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support4{{CompatVersionUnknown}}{{CompatGeckoDesktop(1.9.1)}}10.010.64
Shared workers4{{CompatNo}}{{CompatGeckoDesktop(29)}}{{CompatNo}}10.64
Passing data using structured cloning13{{CompatVersionUnknown}}{{CompatGeckoDesktop(8)}}10.011.56
Passing data using  transferable objects17 {{property_prefix("webkit")}}
+ 21
{{CompatNo}}{{CompatGeckoDesktop(18)}}{{CompatNo}}156
Global {{domxref("window.URL", "URL")}}10[1]
+ 23
{{CompatVersionUnknown}}{{CompatGeckoDesktop(21)}}11156[1]
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidEdgeFirefox Mobile (Gecko)Firefox OS (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support4.44{{CompatVersionUnknown}}{{CompatGeckoMobile(1.9.1)}}1.0.110.011.55.1
Shared workers{{CompatNo}}4{{CompatNo}}291.4{{CompatNo}}{{CompatNo}}{{CompatNo}}
Passing data using structured cloning{{CompatNo}}4{{CompatVersionUnknown}}81.0.1{{CompatNo}}{{CompatNo}}{{CompatNo}}
Passing data using  transferable objects{{CompatNo}}{{CompatNo}}{{CompatNo}}181.0.1{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

[1] As webkitURL.

+ +

Weiterführend

+ + diff --git a/files/de/web/api/webgl_api/index.html b/files/de/web/api/webgl_api/index.html new file mode 100644 index 0000000000..cd699e7ee1 --- /dev/null +++ b/files/de/web/api/webgl_api/index.html @@ -0,0 +1,258 @@ +--- +title: WebGL +slug: Web/API/WebGL_API +tags: + - WebGL + - WebGL2 +translation_of: Web/API/WebGL_API +--- +
{{WebGLSidebar}}
+ +
+

WebGL (Web Graphics Library) ist eine Javascript-API zum Rendern interaktiver 3D und 2D Grafiken mittels eines kompatiblen Web-Browsers ohne Einsatz zusätzlicher Plugins. Mit WebGL steht eine API zur Verfügung, die an OpenGL ES 2.0 angelehnt ist und deren Inhalte mittels eines {{HTMLElement("canvas")}} Elements dargestellt werden.

+
+ +

WebGL steht ab Firefox 4+, Google Chrome 9+, Opera 12+, Safari 5.1+ und Internet Explorer 11+ zur Verfügung. Allerdings muss auch die Hardware des Zielgerätes dieses Feature unterstützen.

+ +

WebGL2 steht ab Firefox 51+, Google Chrome 56+ und Opera 42+ standardmäßig zur Verfügung. WebGL2 wird derzeit nicht von Internet Explorer oder Edge unterstützt.

+ +

Das {{HTMLElement("canvas")}} Element kann auch von Canvas 2D genutzt werden, um 2D Grafiken rendern zu können.

+ +

Reference

+ +
+ +
+ +

Extensions

+ +
+ +
+ +

Events

+ + + +

Konstanten und Typen

+ + + +

Themen

+ +

Die folgenden acht Artikel bauen aufeinander auf.

+ +
+
Einführung in WebGL
+
Wie man einen WebGL-Kontext herstellt.
+
Hinzufügen von 2D Inhalten in einen WebGL-Kontext
+
Wie eine einfache, flache Form mittels WebGL erstellt wird.
+
Farben mittels Shader in einen WebGL-Kontext hinzufügen
+
Zeigt wie Farben mit Shadern auf die Form gebracht werden können.
+
Objekte mit WebGL animieren
+
Erklärt wie Objekte rotiert und verschiebt werden, um eine einfache Animation zu erstellen.
+
3D-Objekte mit WebGL erstellen
+
Erläutert wie dreidimensionale Objekte erstellt und animiert werden (ein Würfel dient als Beispiel).
+
Texturen in WebGL verwenden
+
Demonstriert wie Texturen auf die Oberfläche eines Objektes gezeichnet werden können.
+
Beleuchtung in WebGL
+
Wie Beleuchtungseffekte in unserem WebGL-Kontext simuliert werden.
+
Animierte Texturen in WebGL
+
Animierte Texturen werden mittels einem Ogg-Video auf der Oberfläche eines rotierenden Würfels realisiert.
+
+ +

Ressourcen

+ +
+
WebGL Spezifikation
+
Der Entwurf der WebGL Spezifikation.
+
Khronos WebGL Seite
+
Die Hauptseite für WebGL der Khronos Group.
+
Learning WebGL
+
Eine Reihe von Tutorials über WebGL (Englisch).
+
Das WebGL Kochbuch
+
Rezepte für das Schreiben von WebGL-Code (Englisch).
+
Sylvester
+
Eine Open-Source Bibliothek, die das Verarbeiten von Vektoren und Matrizen erleichtert.
+
Planet WebGL
+
Eine Feed-Sammlung von Leuten, die in der WebGL Community aktiv sind.
+
+ +

Spezifikationen

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpezifikationStatusHinweis
{{SpecName('WebGL')}}{{Spec2('WebGL')}}Grundlegende Definition. Basierend auf OpenGL ES 2.0
{{SpecName('WebGL2')}}{{Spec2('WebGL2')}}Erweiterung von WebGL1. Basierend auf OpenGL ES 3.0.
{{SpecName('OpenGL ES 2.0')}}{{Spec2('OpenGL ES 2.0')}} 
{{SpecName('OpenGL ES 3.0')}}{{Spec2('OpenGL ES 3.0')}} 
+ +

Browser-Kompatibilität

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureEdgeFirefox (Gecko)ChromeInternet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatGeckoDesktop("2.0")}}91112[1]5.1[1]
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureEdgeFirefox Mobile (Gecko)Chrome for AndroidIE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}425[1]{{CompatNo}}12[1]8.1
+
+ +

[1] Die Implementierung dieses Features ist experimentell.

+ +

Kompatibilitätshinweise

+ +

Neben dem Browser muss auch die GPU selbst dieses Feature unterstützen. So ist zum Beispiel S3 Texture Compression (S3TC) derzeit nur auf Desktop-Rechnern und Tegra-basierenden Tablets verfügbar. Die meisten Browser stellen den {{domxref("HTMLCanvasElement.getContext", "WebGL-Context")}} durch den webgl Contextnamen zur Verfügung - ältere Browser benötigen hingegen manchmal stattdessen den Contextnamen experimental-webgl.

+ +

Das kommende WebGL 2 ist vollständig abwärtskompatibel und wird über den Contextnamen experimental-webgl2 aufgerufen. Ab Firefox 42.0 ist der Aufruf auch über den Contextnamen webgl2 möglich - WebGL2 ist bis einschließlich Firefox 50 ein experimentelles Feature und kann zu Testzwecken über Flag-Settings des Konfigurationseditors aktiviert werden. WebGL2 ist ab Firefox 51+, Chrome 56+ und Opera 42+ standardmäßig aktiviert - Internet Explorer und Edge bieten derzeit noch keinen Support für WebGL2.

+ +

Anmerkungen zu Gecko

+ +

WebGL Debugging und Testing

+ +

Ab Gecko 10.0 {{geckoRelease("10.0")}} werden zwei Möglichkeiten geboten, die WebGL-Fähigkeit des Browsers zu Testzwecken zu beeinflussen:

+ +
+
webgl.min_capability_mode
+
Ein boolescher Wert, der bei true einen minimalen Kompatibiätsmodus zur Verfügung stellt. Ist dieser Modus aktiviert, wird WebGL ausschließlich mit dem geringsten Features betrieben, die von der WebGL-Spezifikation definiert wurden. Damit lässt sich sicherstellen, dass dein WebGL-Code auf jedem Gerät unabhängig besonderer Fähigkeiten lauffähig ist. Der Standarardwert ist false.
+
webgl.disable_extensions
+
Ein boolescher Wert, der bei true alle WebGL Extensions deaktiviert. Der Standarardwert ist false.
+
+ +

WebGL2 Aktivierung

+ +
+
webgl.enable-prototype-webgl2 (ab Firefox 38)
+
webgl.enable-webgl2 (ab Firefox 50)
+
Ein boolescher Wert, der bei true den bisher experimentellen WebGL2-Context im Browser aktiviert. Der Standarardwert ist false - ab Firefox 51 ist der Standardwert true.
+
+ +

Siehe auch

+ + diff --git a/files/de/web/api/webgl_api/tutorial/3d-objekte_mit_webgl_erstellen/index.html b/files/de/web/api/webgl_api/tutorial/3d-objekte_mit_webgl_erstellen/index.html new file mode 100644 index 0000000000..d3a21591fd --- /dev/null +++ b/files/de/web/api/webgl_api/tutorial/3d-objekte_mit_webgl_erstellen/index.html @@ -0,0 +1,126 @@ +--- +title: 3D-Objekte mit WebGL erstellen +slug: Web/API/WebGL_API/Tutorial/3D-Objekte_mit_WebGL_erstellen +tags: + - Tutorial + - WebGL +translation_of: Web/API/WebGL_API/Tutorial/Creating_3D_objects_using_WebGL +--- +

{{WebGLSidebar("Tutorial")}} {{PreviousNext("Web/API/WebGL_API/Tutorial/Objekte_mit_WebGL_animieren", "Web/API/WebGL_API/Tutorial/Texturen_in_WebGL_verwenden")}}

+ +

Bringen wir unser Quadrat in die dritte Dimension, indem wir fünf oder mehr Flächen hinzufügen und daraus einen Würfel machen. Um das effizient zu machen, wechseln wir vom Zeichnen direkt über die Vertices zur gl.drawArray() Methode, um den Vertex-Array als eine Tabelle zu verwenden und die einzelnen Vertices in dieser Tabelle als Referenz für Positionen jeder Fläche zu definieren, indem wir gl.drawElements() aufrufen.

+ +

Bedenken Sie: Jede Fläche benötigt vier Vertices, die diese definieren, aber jeder Vertex wird von drei Flächen verwendet. Wir können eine Menge Daten sparen, indem wir eine Liste aller 24 Vertices erstellen und uns dann auf jeden Vertex durch dessen Index in der Liste beziehen, anstatt den gesamten Koordinatensatz zu verwenden.

+ +

Die Vertex-Positionen des Würfels definieren

+ +

Zunächst wollen wir den Positionsspeicher der Vertices erstellen, indem wir den Code in initBuffers() ändern. Das geschieht genau so wie für das Quadrat, allerdings haben wir hier ein paar Datensätze mehr, da wir 24 Vertices (4 pro Seite) haben müssen:

+ +
  var vertices = [
+    // vordere Fläche
+    -1.0, -1.0,  1.0,
+     1.0, -1.0,  1.0,
+     1.0,  1.0,  1.0,
+    -1.0,  1.0,  1.0,
+
+    // hintere Fläche
+    -1.0, -1.0, -1.0,
+    -1.0,  1.0, -1.0,
+     1.0,  1.0, -1.0,
+     1.0, -1.0, -1.0,
+
+    // obere Fläche
+    -1.0,  1.0, -1.0,
+    -1.0,  1.0,  1.0,
+     1.0,  1.0,  1.0,
+     1.0,  1.0, -1.0,
+
+    // untere Fläche
+    -1.0, -1.0, -1.0,
+     1.0, -1.0, -1.0,
+     1.0, -1.0,  1.0,
+    -1.0, -1.0,  1.0,
+
+    // rechte Fläche
+     1.0, -1.0, -1.0,
+     1.0,  1.0, -1.0,
+     1.0,  1.0,  1.0,
+     1.0, -1.0,  1.0,
+
+    // linke Fläche
+    -1.0, -1.0, -1.0,
+    -1.0, -1.0,  1.0,
+    -1.0,  1.0,  1.0,
+    -1.0,  1.0, -1.0
+  ];
+
+ +

Die Farben der Vertices definieren

+ +

Außerdem müssen wir einen Array für die Farben der 24 Vertices erstellen. Dieser Code definiert zunächst die Farben für jede Fläche und verwendet dann eine Schleife, um jeden der Vertices mit einer Farbe zu bestücken.

+ +
  var colors = [
+    [1.0,  1.0,  1.0,  1.0],    // vordere Fläche: weiß
+    [1.0,  0.0,  0.0,  1.0],    // hintere Fläche: rot
+    [0.0,  1.0,  0.0,  1.0],    // obere Fläche: grün
+    [0.0,  0.0,  1.0,  1.0],    // untere Fläche: blau
+    [1.0,  1.0,  0.0,  1.0],    // rechte Fläche: gelb
+    [1.0,  0.0,  1.0,  1.0]     // linke Fläche: violett
+  ];
+
+  var generatedColors = [];
+
+  for (j=0; j<6; j++) {
+    var c = colors[j];
+
+    for (var i=0; i<4; i++) {
+      generatedColors = generatedColors.concat(c);
+    }
+  }
+
+  cubeVerticesColorBuffer = gl.createBuffer();
+  gl.bindBuffer(gl.ARRAY_BUFFER, cubeVerticesColorBuffer);
+  gl.bufferData(gl.ARRAY_BUFFER, new WebGLFloatArray(generatedColors), gl.STATIC_DRAW);
+
+ +

Das Element-Array definieren

+ +

Sobald die Vertex-Arrays generiert worden sind, müssen wir das Element-Array erstellen.

+ +
  cubeVerticesIndexBuffer = gl.createBuffer();
+  gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, cubeVerticesIndexBuffer);
+
+  // Dieser Array definiert jede Fläche als zwei Dreiecke über die Indizes
+  // im Vertex-Array, um die Position jedes Dreiecks festzulegen.
+
+  var cubeVertexIndices = [
+    0,  1,  2,      0,  2,  3,    // vorne
+    4,  5,  6,      4,  6,  7,    // hinten
+    8,  9,  10,     8,  10, 11,   // oben
+    12, 13, 14,     12, 14, 15,   // unten
+    16, 17, 18,     16, 18, 19,   // rechts
+    20, 21, 22,     20, 22, 23    // links
+  ]
+
+  // Sende nun das Element-Array zum GL
+
+  gl.bufferData(gl.ELEMENT_ARRAY_BUFFER,
+      new WebGLUnsignedShortArray(cubeVertexIndices), gl.STATIC_DRAW);
+
+ +

Das cubeVertexIndices Array definiert jede Fläche als ein paar von Dreiecken, alle Vertices des Dreiecks werden als ein Index im Vertex-Array des Würfels festgelegt. Daher ist der Würfel aus einer Sammlung von 12 Dreiecken beschrieben.

+ +

Den Würfel zeichnen

+ +

Als nächstes müssen wir etwas Code zur drawScene() Funktion hinzufügen, um über den Indexspeicher des Würfels zu zeichnen. Wir fügen neue bindBuffer() und drawElements() Aufrufe hinzu:

+ +
  gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, cubeVerticesIndexBuffer);
+  setMatrixUniforms();
+  gl.drawElements(gl.TRIANGLES, 36, gl.UNSIGNED_SHORT, 0);
+
+ +

Da jede Seite unseres Würfels aus zwei Dreiecken besteht, gibt es 6 Vertices pro Seite, oder 36 Vertices im Würfel, obwohl einige davon doppelt sind. Da unser Index-Array jedoch aus einfachen Integern besteht, stellt dies keinen unkoordinierbaren Betrag an Daten dar, welcher für jeden Frame der Animation durchgegangen werden muss.

+ +

Jetzt haben wir einen animierten Würfel, welcher herum springt, rotiert und über sechs unterschiedliche Seiten verfügt. Wenn Ihr Browser WebGL unterstützt, schauen Sie sich hier die Demo in Aktion an.

+ +

{{PreviousNext("Web/API/WebGL_API/Tutorial/Objekte_mit_WebGL_animieren", "Web/API/WebGL_API/Tutorial/Texturen_in_WebGL_verwenden")}}

diff --git a/files/de/web/api/webgl_api/tutorial/animierte_texturen_in_webgl/index.html b/files/de/web/api/webgl_api/tutorial/animierte_texturen_in_webgl/index.html new file mode 100644 index 0000000000..bfeb362b8e --- /dev/null +++ b/files/de/web/api/webgl_api/tutorial/animierte_texturen_in_webgl/index.html @@ -0,0 +1,89 @@ +--- +title: Animierte Texturen in WebGL +slug: Web/API/WebGL_API/Tutorial/Animierte_Texturen_in_WebGL +tags: + - Tutorial + - WebGL +translation_of: Web/API/WebGL_API/Tutorial/Animating_textures_in_WebGL +--- +

{{WebGLSidebar("Tutorial") }} {{Previous("Web/API/WebGL_API/Tutorial/Beleuchtung_in_WebGL")}}

+ +

In dieser Demo bauen wir auf das vorherige Beispiel auf, indem wir die statischen Texturen mit den Frames eines OGG-Video ersetzen. Das ist nicht sehr schwer zu schreiben, sieht aber umso besser aus. Fangen wir an.

+ +

Zugang zum Video

+ +

Zunächst müssen wir etwas HTML hinzufügen, um das video Element zu erstellen, welches wir verwenden, um die Video-Frames zu erhalten:

+ +
<video id="video" src="Firefox.ogv" autobuffer='true'">
+  Ihr Browser scheint das HTML5 <code>&lt;video&gt;</code> Element nicht zu unterstützen.
+</video>
+
+ +

Das erstellt einfach ein Element, um die Video-Datei "Firefox.ogv" abzuspielen. Wir benutzen CSS, um zu verhindern, dass das Video angezeigt wird:

+ +
video {
+  display: none;
+}
+
+ +

Dann schenken wir dem JavaScript Code wieder unsere Aufmerksamkeit und fügen eine neue Zeile zur start() Funktion hinzu, um einen Bezug zum Video-Element herzustellen:

+ +
videoElement = document.getElementById("video");
+
+ +

Und wir ersetzen den Code, der die Intervall-gesteuerten Aufrufe von drawScene() setzt, mit diesem Code:

+ +
videoElement.addEventListener("canplaythrough", startVideo, true);
+videoElement.addEventListener("ended", videoDone, true);
+
+ +

Die Idee ist hier, dass wir die Animation nicht starten wollen, bevor das Video nicht ausreichend zwischengespeichert wurde, sodass es dann ohne Unterbrechung abgespielt werden kann. Wir fügen also einen Event-Listener hinzu, um auf das video Element zu warten bis es uns mitteilt, dass genug zwischengespeichert wurde und das komplette Video ohne Pause abgespielt werden kann. Wir fügen außerdem einen zweiten Event-Listener hinzu, sodass wir die Animation stoppen können, wenn das Video beendet ist und wir so nicht unnötig den Prozessor belasten.

+ +

Die startVideo() Funktion sieht so aus:

+ +
function startVideo() {
+  videoElement.play();
+  videoElement.addEventListener("timeupdate", updateTexture, true);
+  setInterval(drawScene, 15);
+}
+
+ +

Hier wird einfach das Video gestartet und ein Event-Handler bereitgestellt, der aufgerufen wird, wenn ein neuer Frame des Videos verfügbar ist. Dann werden die Intervall-gesteuerten Aufrufe der drawScene() Funktion eingerichtet, um den Würfel zu rendern.

+ +

Die videoDone() Funktion ruft einfach {{ domxref("window.clearInterval") }} auf, um die Intervallaufrufe zu beenden, die die Animation aktualisieren.

+ +

Die Video-Frames als Textur verwenden

+ +

Die nächste Änderung erhält die initTexture() Funktion, welche viel einfacher wird, weil kein Bild mehr geladen werden muss. Stattdessen muss nun das Textur-Mapping aktiviert werden und ein leeres Textur-Objekt zum späteren Gebrauch erstellt werden:

+ +
function initTextures() {
+  gl.enable(gl.TEXTURE_2D);
+  cubeTexture = gl.createTexture();
+}
+
+ +

So sieht die updateTexture() Funktion aus. Hier wird wirklich Arbeit verrichtet:

+ +
function updateTexture() {
+  gl.bindTexture(gl.TEXTURE_2D, cubeTexture);
+  gl.texImage2D(gl.TEXTURE_2D, 0, videoElement, true);
+  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
+  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_NEAREST);
+  gl.generateMipmap(gl.TEXTURE_2D);
+  gl.bindTexture(gl.TEXTURE_2D, null);
+}
+
+ +

Sie kennen diesen Code bereits. Es ist fast identisch zur handleTextureLoaded() Routine im vorherigen Beispiel, mit der Ausnahme, dass wir texImage2D() nicht mit einem Image Objekt sondern mit dem video Element aufrufen.

+ +

updateTexture() wird jedes Mal aufgerufen, wenn sich das timeupdate Event vom video Element meldet. Dieses Event wird gesendet, wenn sich die Zeit des aktuellen Frames ändert, sodass wir wissen, dass wir unsere Textur nur dann aktualisieren müssen, wenn neue Daten verfügbar sind.

+ +

Das war alles! Wenn Sie eine Browser mit Unterstützung von WebGL verwenden, können Sie sich das Beispiel in Aktion ansehen.

+ +

Siehe auch

+ + + +

{{Previous("Web/API/WebGL_API/Tutorial/Beleuchtung_in_WebGL")}}

diff --git a/files/de/web/api/webgl_api/tutorial/beleuchtung_in_webgl/index.html b/files/de/web/api/webgl_api/tutorial/beleuchtung_in_webgl/index.html new file mode 100644 index 0000000000..bd65b5bb40 --- /dev/null +++ b/files/de/web/api/webgl_api/tutorial/beleuchtung_in_webgl/index.html @@ -0,0 +1,172 @@ +--- +title: Beleuchtung in WebGL +slug: Web/API/WebGL_API/Tutorial/Beleuchtung_in_WebGL +tags: + - Tutorial + - WebGL +translation_of: Web/API/WebGL_API/Tutorial/Lighting_in_WebGL +--- +

{{WebGLSidebar("Tutorial")}} {{PreviousNext("Web/API/WebGL_API/Tutorial/Texturen_in_WebGL_verwenden", "Web/API/WebGL_API/Tutorial/Animierte_Texturen_in_WebGL")}}

+ +

Als Erstes sollten wir verstehen, dass WebGL nicht wie OpenGL über eine eigene Unterstützung für die Beleuchtung verfügt. Das müssen wir selbst machen. Glücklicherweise ist es nicht sehr schwer und dieser Artikel versucht Ihnen die Grundlagen dazu näher zu bringen.

+ +

Beleuchtung und Schattierung simulieren

+ +

Obwohl wir nicht weiter ins Detail über die Theorie hinter simulierter Beleuchtung in 3D Grafiken gehen wollen, was außerdem weit über diesen Artikel hinaus gehen würde, ist es gut zu wissen wie es ungefähr funktioniert. Anstatt hier nun in aller Tiefe zu diskutieren, sollten Sie einen Blick auf den »Phong Shading« Artikel auf Wikipedia werfen, welcher einen guten Überblick über das meist genutzte Beleuchtungsmodell liefert.

+ +

Es gibt drei grundlegende Typen zur Beleuchtung:

+ +

Umgebungslicht ist das Licht, das die Szene umgibt. Es weist in keine Richtung und bestrahlt jede Oberfläche in gleicher Weise, egal in welche Richtung es zeigt.

+ +

Gerichtetes Licht ist das Licht, das von einer festgelegten Richtung ausgestrahlt wird. Dieses Licht ist so weit weg, sodass sich jeder Photon parallel zu jedem anderen Photon bewegt. Sonnenlicht ist zum Beispiel gerichtetes (direktionales) Licht.

+ +

Punktbeleuchtung ist das Licht, das von einem Punkt ausgestrahlt wird und von dort radial in alle Richtungen verläuft. So funktionieren zum Beispiel die Glühbirnen im Alltag.

+ +

Für unsere Zwecke vereinfachen wir das Beleuchtungsmodell, indem wir nur gerichtetes Licht und Umgebungslicht betrachten. Wir haben hier keine Highlights, die wir mit Punktbeleuchtung oder Glanzlicht in dieser Szene hervorheben wollen. Stattdessen werden wir Umgebungslicht mit einem einzelnen, gerichteten Licht verwenden, welches auf den rotierenden Würfel aus der vorherigen Demo zeigt.

+ +

Wenn Sie die Konzepte der Punktbeleuchtung und des Glanzlichtes hinter sich gelassen haben, gibt es dennoch zwei kleine Informationen, die Sie benötigen werden, wenn wir unser gerichtetes Licht implementieren:

+ +
    +
  1. Wir müssen die Oberflächennormale mit jedem Vertex verbinden. Das ist ein Vektor, der senkrecht zur Oberfläche des Vertex ist.
  2. +
  3. Wir müssen die Richtung in welche das Licht strahlt wissen. Diese wird durch den Richtungsvektor angegeben.
  4. +
+ +

Dann aktualisieren wir den Vertex-Shader, um die Farbe jedes Vertices, unter Berücksichtigung des Umgebungslichts und dem Effekt des gerichteten Lichts (sowie dessen Winkel mit dem es auf die Oberfläche trifft), einzustellen. Wir werden sehen, wie genau wir das machen, wenn wir einen Blick auf den Code für den Shader werfen.

+ +

Die Normalen für die Vertices erstellen

+ +

Als Erstes müssen wir einen Array für die Normalen für alle Vertices erstellen, die unseren Würfel umfassen. Da ein Würfel ein sehr einfaches Objekt ist, ist dies auch sehr einfach zu erstellen. Für komplexere Objekte wird das Berechnen der Normalen schon umfassender.

+ +
  cubeVerticesNormalBuffer = gl.createBuffer();
+  gl.bindBuffer(gl.ARRAY_BUFFER, cubeVerticesNormalBuffer);
+
+  var vertexNormals = [
+    // vorne
+     0.0,  0.0,  1.0,
+     0.0,  0.0,  1.0,
+     0.0,  0.0,  1.0,
+     0.0,  0.0,  1.0,
+
+    // hinten
+     0.0,  0.0, -1.0,
+     0.0,  0.0, -1.0,
+     0.0,  0.0, -1.0,
+     0.0,  0.0, -1.0,
+
+    // oben
+     0.0,  1.0,  0.0,
+     0.0,  1.0,  0.0,
+     0.0,  1.0,  0.0,
+     0.0,  1.0,  0.0,
+
+    // unten
+     0.0, -1.0,  0.0,
+     0.0, -1.0,  0.0,
+     0.0, -1.0,  0.0,
+     0.0, -1.0,  0.0,
+
+    // rechts
+     1.0,  0.0,  0.0,
+     1.0,  0.0,  0.0,
+     1.0,  0.0,  0.0,
+     1.0,  0.0,  0.0,
+
+    // links
+    -1.0,  0.0,  0.0,
+    -1.0,  0.0,  0.0,
+    -1.0,  0.0,  0.0,
+    -1.0,  0.0,  0.0
+  ];
+
+  gl.bufferData(gl.ARRAY_BUFFER, new WebGLFloatArray(vertexNormals), gl.STATIC_DRAW);
+
+ +

Das sollte Ihnen schon bekannt vorkommen: Wir erstellen einen neuen Buffer, verknüpfen den Array damit und senden dann unseren Vertex-Normalen-Array in den Buffer, indem wir bufferData() aufrufen.

+ +

Dann fügen wir Code zu drawScene() hinzu, um das Normalen-Array mit einem Shader-Attribut zu verknüpfen, sodass der Shader-Code darauf zugreifen kann:

+ +
  gl.bindBuffer(gl.ARRAY_BUFFER, cubeVerticesNormalBuffer);
+  gl.vertexAttribPointer(vertexNormalAttribute, 3, gl.FLOAT, false, 0, 0);
+
+ +

Schließlich müssen wir den Code aktualisieren, welcher die Einheitsmatrizen erstellt, um eine Normalenmatrix zu generieren und zum Shader auszuliefern. Diese wird verwendet, um die Normalen umzuwandeln, wenn die aktuelle Orientierung des Würfels in Beziehung zur Lichtquelle behandelt wird:

+ +
  var normalMatrix = mvMatrix.inverse();
+  normalMatrix = normalMatrix.transpose();
+  var nUniform = gl.getUniformLocation(shaderProgram, "uNormalMatrix");
+  gl.uniformMatrix4fv(nUniform, false, new WebGLFloatArray(normalMatrix.flatten()));
+
+ +

Die Shader aktualisieren

+ +

Jetzt sind alle Daten, die von den Shadern gebraucht werden, verfügbar. Wir müssen nun den Code in den Shadern selbst aktualisieren.

+ +

Der Vertex-Shader

+ +

Zunächst aktualisieren wir den Vertex-Shader, sodass dieser einen Schattenwert für jeden Vertex auf Basis des Umgebungslichts sowie des direktionalen Lichts berechnet. Werfen wir einen Blick auf den Code:

+ +
    <script id="shader-vs" type="x-shader/x-vertex">
+      attribute vec3 aVertexNormal;
+      attribute vec3 aVertexPosition;
+      attribute vec2 aTextureCoord;
+
+      uniform mat4 uNormalMatrix;
+      uniform mat4 uMVMatrix;
+      uniform mat4 uPMatrix;
+
+      varying vec2 vTextureCoord;
+      varying vec3 vLighting;
+
+      void main(void) {
+        gl_Position = uPMatrix * uMVMatrix * vec4(aVertexPosition, 1.0);
+        vTextureCoord = aTextureCoord;
+
+        // Beleuchtungseffekt anwenden
+
+        vec3 ambientLight = vec3(0.6, 0.6, 0.6);
+        vec3 directionalLightColor = vec3(0.5, 0.5, 0.75);
+        vec3 directionalVector = vec3(0.85, 0.8, 0.75);
+
+        vec4 transformedNormal = uNormalMatrix * vec4(aVertexNormal, 1.0);
+
+        float directional = max(dot(transformedNormal.xyz, directionalVector), 0.0);
+        vLighting = ambientLight + (directionalLightColor * directional);
+      }
+    </script>
+
+ +

Sobald die Position des Vertex berechnet wurde und wir die Koordinaten des Texels (welcher passend zum Vertex ist) erhalten haben, können wir den Schatten für den Vertex berechnen.

+ +

Als Erstes wandeln wir die Normale auf Basis der aktuellen Position und Orientierung des Würfels um, indem wir die Normale des Vertexes mit der Normalenmatrix multiplizieren. Dann können wir den Betrag an direktionalem Licht, welcher auf den Vertex angewendet werden soll, berechnen, indem wir das Skalarprodukt der umgewandelten Normalen und des direktionalen Vektors (Richtung aus der das Licht kommt) bilden. Wenn dieser Wert kleiner als Null ist, setzen wir den Wert auf Null fest, da man nicht weniger als Null Licht haben kann.

+ +

Wenn der Betrag des direktionalen Lichts berechnet wurde, können wir den Beleuchtungswert generieren, indem wir das Umgebungslicht nehmen und das Produkt der Farbe des direktionalen Lichts und den Betrag an direktionalem Licht bereitstellen. Als Ergebnis haben wir nun einen RGB-Wert, welcher vom Fragment-Shader verwendet wird, um die Farbe jedes Pixels den wir rendern einzustellen.

+ +

Der Fragment-Shader

+ +

Der Fragment-Shader muss nun aktualisiert werden, um den berechneten Beleuchtungswert vom Vertex-Shader zu berücksichtigen:

+ +
    <script id="shader-fs" type="x-shader/x-fragment">
+      varying vec2 vTextureCoord;
+      varying vec3 vLighting;
+
+      uniform sampler2D uSampler;
+
+      void main(void) {
+        vec4 texelColor = texture2D(uSampler, vec2(vTextureCoord.s, vTextureCoord.t));
+
+        gl_FragColor = vec4(texelColor.rgb * vLighting, texelColor.a);
+      }
+    </script>
+
+ +

Hier erhalten wir nun die Farbe des Texels, genau so wie wir es im vorherigen Beispiel getan haben. Bevor wir die Farbe der Fragmente aber festlegen, multiplizieren wir die Texel-Farbe mit dem Beleuchtungswert, um die Texel-Farbe so einzustellen, dass diese den Effekt der Lichtquelle berücksichtigt.

+ +

Und das war's! Wenn Sie einen Browser verwenden, der WebGL unterstützt, können Sie einen Blick auf die Live-Demo werfen.

+ +

Übungen für den Leser

+ +

Dies ist natürlich ein sehr einfaches Beispiel, welches eine Beleuchtung pro Vertex implementiert. Für fortgeschrittene Grafiken, möchten Sie sicher eine Beleuchtung pro Pixel implementieren, aber dies wird Sie in die Richtung leiten.

+ +

Sie können nun also versuchen mit der Richtung der Lichtquelle zu experimentieren, die Farbe der Leuchtquelle zu ändern und so weiter.

+ +

{{PreviousNext("Web/API/WebGL_API/Tutorial/Texturen_in_WebGL_verwenden", "Web/API/WebGL_API/Tutorial/Animierte_Texturen_in_WebGL")}}

diff --git "a/files/de/web/api/webgl_api/tutorial/einf\303\274hrung_in_webgl/index.html" "b/files/de/web/api/webgl_api/tutorial/einf\303\274hrung_in_webgl/index.html" new file mode 100644 index 0000000000..5906f95761 --- /dev/null +++ "b/files/de/web/api/webgl_api/tutorial/einf\303\274hrung_in_webgl/index.html" @@ -0,0 +1,73 @@ +--- +title: Einführung in WebGL +slug: Web/API/WebGL_API/Tutorial/Einführung_in_WebGL +tags: + - Tutorial + - WebGL +translation_of: Web/API/WebGL_API/Tutorial/Getting_started_with_WebGL +--- +

{{WebGLSidebar("Tutorial")}} {{Next("Web/API/WebGL_API/Tutorial/Hinzufügen_von_2D_Inhalten_in_einen_WebGL-Kontext")}}

+ +

Mit WebGL steht eine API zur Verfügung, die auf OpenGL ES 2.0 basiert, um 3D Rendering im HTML canvas Element zu ermöglichen. WebGL Programme bestehen aus Steuercode in JavaScript und Shadercode (GLSL), der auf dem Grafikprozessor (GPU) des Computers ausgeführt wird. WebGL Elemente können mit anderen HTML Elementen kombiniert werden.

+ +

Dieser Artikel ist eine Einführung in die Grundlagen von WebGL. Es wird vorausgesetzt, dass einige mathematischen Kenntnisse im 3D-Bereich (Matrizen) vorhanden sind. Dieser Artikel wird daher keine 3D-Grafik-Konzepte vermitteln. Es gibt einen anfängergeeigneten Leitfaden mit Programmieraufgaben in unserem Lernbereich: Learn WebGL for 2D and 3D graphics.

+ +

DIe hier verwendeten Codebeispiele finden sich auch im webgl-examples GitHub repository.

+ +

3D Rendering vorbereiten

+ +

Um WebGL benutzen zu können, wird als erstes ein canvas Element benötigt. Der folgende HTML-Code definiert eine canvas Zeichenfläche.

+ +
<body>
+  <canvas id="glCanvas" width="640" height="480"></canvas>
+</body>
+
+ +

Vorbereitung des WebGL-Kontexts

+ +

Die main() Funktion im JavaScript Code wird aufgerufen, nachdem das Dokument geladen wurde. Die Aufgabe der Funktion ist, den WebGL-Kontext festzulegen und mit dem Rendering zu beginnen.

+ +
main();
+
+function main() {
+  const canvas = document.querySelector("#glCanvas");
+  // Initialisierung des GL Kontexts
+  const gl = canvas.getContext("webgl");
+
+  // Nur fortfahren, wenn WebGL verfügbar ist und funktioniert
+  if (!gl) {
+    alert("Unable to initialize WebGL. Your browser or machine may not support it.");
+    return;
+  }
+
+  // Setze clear color auf schwarz, vollständig sichtbar
+  gl.clearColor(0.0, 0.0, 0.0, 1.0);
+  // Lösche den color buffer mit definierter clear color
+  gl.clear(gl.COLOR_BUFFER_BIT);
+}
+ +

Als erstes verschaffen wir uns eine Referenz zum canvas Element und speichern sie in der canvas Variable.

+ +

Sobald wir den Bezug zum canvas haben, versuchen wir einen zugehörigen  WebGLRenderingContext zu erhalten, indem wir getContext aufrufen und dabei den String "webgl" mitgeben. Falls der Browser WebGL nicht unterstützt, wird getContext null zurückgeben, woraufhin wir den Nutzer benachrichtigen und das Script verlassen.

+ +

Wenn der Kontext erfolgreich initialisiert wurde, ist gl eine Variable für den Kontext. In diesem Fall setzen wir die clear color auf schwarz, und löschen den zugehörigen Kontext (der canvas wird mit der Hintergrundfarbe neu gezeichnet)

+ +

An dieser Stelle ist genug Code vorhanden, um den WebGL-Kontext erfolgreich zu initialisieren. Ein großer, leerer, schwarzer Kasten sollte zu sehen sein, der darauf wartet mit weiteren Inhalten gefüttert zu werden.

+ +

{{EmbedGHLiveSample('webgl-examples/tutorial/sample1/index.html', 670, 510) }}

+ +

Vollständigen Code ansehen | Demo in neuer Seite öffnen

+ +

Siehe auch

+ +

 

+ + + +

 

+ +

{{Next("Web/API/WebGL_API/Tutorial/Hinzufügen_von_2D_Inhalten_in_einen_WebGL-Kontext")}}

diff --git "a/files/de/web/api/webgl_api/tutorial/farben_mittels_shader_in_einen_webgl-kontext_hinzuf\303\274gen/index.html" "b/files/de/web/api/webgl_api/tutorial/farben_mittels_shader_in_einen_webgl-kontext_hinzuf\303\274gen/index.html" new file mode 100644 index 0000000000..94068822d5 --- /dev/null +++ "b/files/de/web/api/webgl_api/tutorial/farben_mittels_shader_in_einen_webgl-kontext_hinzuf\303\274gen/index.html" @@ -0,0 +1,97 @@ +--- +title: Farben mittels Shader in einen WebGL-Kontext hinzufügen +slug: >- + Web/API/WebGL_API/Tutorial/Farben_mittels_Shader_in_einen_WebGL-Kontext_hinzufügen +tags: + - Tutorial + - WebGL +translation_of: Web/API/WebGL_API/Tutorial/Using_shaders_to_apply_color_in_WebGL +--- +

{{WebGLSidebar("Tutorial")}} {{PreviousNext("Web/API/WebGL_API/Tutorial/Hinzufügen_von_2D_Inhalten_in_einen_WebGL-Kontext", "Web/API/WebGL_API/Tutorial/Objekte_mit_WebGL_animieren")}}

+ +

Wir haben ein simples Quadrat im vorherigen Teil erstellt, im nächsten Schritt wollen wir ein bisschen Farbe ins Spiel bringen. Dafür sind Änderungen an den Shadern erforderlich.

+ +

Farben zu den Eckpunkten hinzufügen

+ +

In der Computergrafik werden Objekte mit einer Reihe von Punkten erstellt. Jeder Punkt hat eine Position und eine Farbe. Standardmäßig werden alle anderen Pixelfarben (und alle weiteren Attribute, darunter die Position) über eine lineare Interpolation berechnet, die automatisch glatte Verläufe erstellt. Vorher hat unser Vertex-Shader keine festgelegten Farben auf die Punkte (Vertices) angewendet und der Fragment-Shader legte die feste Farbe weiß für jeden Pixel fest, sodass das gesamte Quadrat komplett weiß gezeichnet wurde.

+ +

Nun wollen wir in jeder Ecke des Quadrats einen Verlauf in einer unterschiedlichen Farbe rendern: rot, blau, grün und weiß. Als erstes sollten wir daher diese Farben in den vier Eckpunkten einrichten. Um das zu machen, müssen wir zunächst einen Array der Vertex-Farben erstellen und diesen dann in einen WebGL Buffer speichern. Das erreichen wir durch die folgenden Zeilen in unserer initBuffers() Funktion:

+ +
var colors = [
+  1.0,  1.0,  1.0,  1.0,    // weiß
+  1.0,  0.0,  0.0,  1.0,    // rot
+  0.0,  1.0,  0.0,  1.0,    // grün
+  0.0,  0.0,  1.0,  1.0     // blau
+];
+
+squareVerticesColorBuffer = gl.createBuffer();
+gl.bindBuffer(gl.ARRAY_BUFFER, squareVerticesColorBuffer);
+gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(colors), gl.STATIC_DRAW);
+}
+
+ +

Dieser Code definiert zuerst einen JavaScript Array, welcher die vier Farb-Vektoren mit jeweils vier Werten für die jeweilige Farbe enthält. Dann wird ein neuer WebGL Buffer angewiesen diese Farben zu speichern und der Array wird in WebGL Floats konvertiert und im Buffer gespeichert.

+ +

Um die Farben schließlich zu verwenden, muss der der Vertex-Shader aktualisiert werden, um die entsprechende Farbe vom Farb-Buffer zu erhalten:

+ +
<script id="shader-vs" type="x-shader/x-vertex">
+  attribute vec3 aVertexPosition;
+  attribute vec4 aVertexColor;
+
+  uniform mat4 uMVMatrix;
+  uniform mat4 uPMatrix;
+
+  varying vec4 vColor;
+
+  void main(void) {
+    gl_Position = uPMatrix * uMVMatrix * vec4(aVertexPosition, 1.0);
+    vColor = aVertexColor;
+  }
+</script>
+
+ +

Der wichtigste Unterschied ist hier, dass wir für jeden Punkt (Vertex) die Farbe entsprechend des Farb-Arrays setzen.

+ +

Die Fragmente mit Farben versehen

+ +

Als Erinnerung, so sah unser Fragment-Shader vorher aus:

+ +
<script id="shader-fs" type="x-shader/x-fragment">
+  void main(void) {
+    gl_FragColor = vec4(1.0, 1.0, 1.0, 1.0);
+  }
+</script>
+
+ +

Um nun die interpolierte Farbe für jeden Pixel aufzugreifen, müssen wir dies einfach so ändern, dass wir den Wert der vColor Variable erhalten:

+ +
<script id="shader-fs" type="x-shader/x-fragment">
+  varying vec4 vColor;
+
+  void main(void) {
+    gl_FragColor = vColor;
+  }
+</script>
+
+ +

Das ist eine sehr einfache Änderung. Anstatt des festen Wertes vorher, erhält jedes Fragment jetzt einfach die interpolierte Farbe, basierend auf der Position relativ zu den Kontenpunkten (Vertices).

+ +

Mit den Farben zeichnen

+ +

Als nächstes ist es nötig, Code zur initShaders() Routine hinzuzufügen, um das Farbattribut für das Shader-Programm zu initialisieren:

+ +
  vertexColorAttribute = gl.getAttribLocation(shaderProgram, "aVertexColor");
+  gl.enableVertexAttribArray(vertexColorAttribute);
+
+ +

Dann wird drawScene() abgeändert, um schließlich die Farben zu verwenden, wenn das Quadrat gezeichnet wird:

+ +
  gl.bindBuffer(gl.ARRAY_BUFFER, squareVerticesColorBuffer);
+  gl.vertexAttribPointer(vertexColorAttribute, 4, gl.FLOAT, false, 0, 0);
+
+ +

Jetzt sollten Sie das Beispiel in einem WebGL kompatiblen Browser sehen und Ihre Ausgabe sollte so wie im Bild unten gezeichnet werden (das Quadrat ist innerhalb eines schwarzen Felds zu sehen):

+ +

screenshot.png

+ +

{{PreviousNext("Web/API/WebGL_API/Tutorial/Hinzufügen_von_2D_Inhalten_in_einen_WebGL-Kontext", "Web/API/WebGL_API/Tutorial/Objekte_mit_WebGL_animieren")}}

diff --git "a/files/de/web/api/webgl_api/tutorial/hinzuf\303\274gen_von_2d_inhalten_in_einen_webgl-kontext/index.html" "b/files/de/web/api/webgl_api/tutorial/hinzuf\303\274gen_von_2d_inhalten_in_einen_webgl-kontext/index.html" new file mode 100644 index 0000000000..56c267f394 --- /dev/null +++ "b/files/de/web/api/webgl_api/tutorial/hinzuf\303\274gen_von_2d_inhalten_in_einen_webgl-kontext/index.html" @@ -0,0 +1,238 @@ +--- +title: Hinzufügen von 2D Inhalten in einen WebGL-Kontext +slug: Web/API/WebGL_API/Tutorial/Hinzufügen_von_2D_Inhalten_in_einen_WebGL-Kontext +tags: + - WebGL +translation_of: Web/API/WebGL_API/Tutorial/Adding_2D_content_to_a_WebGL_context +--- +

{{WebGLSidebar("Tutorial")}} {{PreviousNext("Web/API/WebGL_API/Tutorial/Einführung_in_WebGL", "Web/API/WebGL_API/Tutorial/Farben_mittels_Shader_in_einen_WebGL-Kontext_hinzufügen")}}

+ +

Sobald der WebGL-Kontext erfolgreich erstellt wurde, können wir anfangen darin zu rendern. Am einfachsten beginnen wir mit einem einfachen, zweidimensionalen, untextuierten Objekt. Fangen wir also damit an, ein Stück Code zu schreiben, um ein Quadrat zu zeichnen.

+ +

Hinweis zur deutschen Übersetzung dieses Abschnitts

+ +

Die deutsche Übersetzung bezieht sich auf ältere Version des Beispielcodes als der englische Originaltext. Der im deutschen Text beschriebene Code hat einige Probleme:

+ + + +

Um das Beispiel selber nachzuprogrammieren ist es daher empfehlenswert, auf die englische Version des Tutorials zu wechseln. Vielleicht haben Sie ja auch Lust, diese Version ins Deutsche zu übersetzen?

+ +

Beleuchtung der Szene

+ +

Das Wichtigste, das wir verstehen müssen bevor wir anfangen können, ist, dass wir, uns bereits in einer dreidimensionalen Umgebung befinden, obwohl wir nur ein zweidimensionales Objekt in diesem Beispiel rendern wollen. Das heißt, wir müssen jetzt bereits Shader einsetzen, die unsere einfache Szene beleuchten und solche erstellen, die unser Objekt zeichnen. Diese Shader werden festlegen wie unser Quadrat später beleuchtet sein wird.

+ +

Initialisierung der Shader

+ +

Shader sind durch die OpenGL ES Shading Language (pdf) spezifiziert. Damit es einfacher ist unsere Inhalte zu warten und zu aktualisieren, können wir unseren Code so schreiben, dass die Shader im HTML Dokument gefunden werden, anstatt alles mittels JavaScript zu bauen. Werfen wir einen Blick auf unsere initShaders() Routine, welche diese Aufgabe übernimmt:

+ +
function initShaders() {
+  var fragmentShader = getShader(gl, "shader-fs");
+  var vertexShader = getShader(gl, "shader-vs");
+
+  // Erzeuge Shader
+
+  shaderProgram = gl.createProgram();
+  gl.attachShader(shaderProgram, vertexShader);
+  gl.attachShader(shaderProgram, fragmentShader);
+  gl.linkProgram(shaderProgram);
+
+  // Wenn die das Aufrufen der Shader fehlschlägt,
+  // gib eine Fehlermeldung aus:
+
+  if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) {
+    alert("Initialisierung des Shaderprogramms nicht möglich.");
+  }
+
+  gl.useProgram(shaderProgram);
+
+  vertexPositionAttribute = gl.getAttribLocation(shaderProgram, "aVertexPosition");
+  gl.enableVertexAttribArray(vertexPositionAttribute);
+}
+
+
+ +

Es werden zwei Shader in dieser Routine geladen; der Erste, der fragmentShader, wird vom script Element mit der Id "shader-fs" geladen. Der Zweite, der vertexShader, wird vom script Element mit der Id "shader-vs" geladen. Wir werden im nächsten Abschnitt noch näher auf die getShader() Funktion eingehen. Diese Routine holt sich dann die Shader aus dem DOM.

+ +

In diesem Teil erstellen wir noch das Shaderprogramm, in dem wir die Funktion createProgram() aufrufen, die beiden Shader anhängen und das Shaderprogramm verlinken. Danach wird der Zustand des LINK_STATUS Parameters überprüft, um sicher zu gehen, dass das Programm erfolgreich verlinkt wurde. Wenn das der Fall ist, aktivieren wir das neue Shaderprogramm.

+ +

Shader aus dem DOM laden

+ +

Die getShader() Routine ruft ein Shaderprogramm mit dem festgelegtem Namen aus dem DOM auf, gibt das kompilierte Shaderprogramm zurück oder ist leer, wenn nichts geladen oder kompiliert worden konnte.

+ +
function getShader(gl, id) {
+  var shaderScript = document.getElementById(id);
+
+  if (!shaderScript) {
+    return null;
+  }
+
+  var theSource = "";
+  var currentChild = shaderScript.firstChild;
+
+  while(currentChild) {
+    if (currentChild.nodeType == 3) {
+      theSource += currentChild.textContent;
+    }
+
+    currentChild = currentChild.nextSibling;
+  }
+ +

Wenn das Element mit der festgelegten Id gefunden wurde, wird der Text in die Variable theSource gespeichert.

+ +
  var shader;
+
+  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 {
+    return null;  // Unbekannter Shadertyp
+  }
+ +

Jetzt wo der Code für die Shader gelesen wurde, können wir uns die MIME Typen der Shader angucken, um festzulegen, ob es ein Vertex-Shader (MIME Typ: "x-shader/x-vertex") oder ein Fragment-Shader (MIME Typ: "x-shader/x-fragment") ist. Danach werden dann die entsprechenden Shadertypen erstellt.

+ +
  gl.shaderSource(shader, theSource);
+
+  // Kompiliere das Shaderprogramm
+
+  gl.compileShader(shader);
+
+  // Überprüfe, ob die Kompilierung erfolgreich war
+
+  if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
+    alert("Es ist ein Fehler beim Kompilieren der Shader aufgetaucht: " + gl.getShaderInfoLog(shader));
+    return null;
+  }
+
+  return shader;
+}
+
+ +

Schließlich wird der Shader kompiliert. Falls ein Fehler während der Kompilierung auftritt, zeigen wir die Fehlermeldung an und geben null zurück. Andernfalls wird der kompilierte Shader zurückgegeben.

+ +

Die Shader

+ +

Nun müssen wir die eigentlichen Shaderprogramme in unser HTML schreiben. Wie genau diese Shader arbeiten, übersteigt das Ziel dieses Tutorials, wir gehen daher nur auf das Wesentliche ein.

+ +

Fragment-Shader

+ +

Jeder Pixel in einem Vieleck wird Fragment in der GL-Fachsprache genannt. Die Aufgabe des Fragment-Shaders ist es, die Farbe für jeden Pixel bereitzustellen. In unserem Fall ordnen wir einfach jedem Pixel eine weiße Farbe zu.

+ +

gl_FragColor ist eine eingebaute GL Variable, die für die Farbe des Fragments verwendet wird.

+ +
<script id="shader-fs" type="x-shader/x-fragment">
+
+  void main(void) {
+    gl_FragColor = vec4(1.0, 1.0, 1.0, 1.0);
+  }
+</script>
+
+ +

Vertex-Shader

+ +

Der Vertex-Shader definiert die Position und Form von jedem Punkt.

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

Das Objekt erstellen

+ +

Bevor wir unser Quadrat rendern können, müssen wir einen Puffer erstellen, der unsere Punkte enthält. Das werden wir mittels einer Funktion machen, die wir initBuffers() nennen. Wenn wir zu mehr fortgeschrittenen WebGL-Konzepten kommen, wird diese Routine vergrößert, um mehr - und komplexere - 3D-Objekte zu erstellen.

+ +
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);
+}
+
+ +

Diese Routine ist, durch die einfache Art der Szene in diesem Beispiel, sehr einfach gehalten. Es geht los mit dem Aufruf der createBuffer() Methode, die einen Puffer erstellt in dem wir die Punkte speichern können. Der Puffer wird, durch Aufrufen der bindBuffer() Methode, mit dem Kontext verbunden.

+ +

Wenn das erledigt ist, erstellen wir einen JavaScript Array, der die Koordinaten für jeden Punkt des Quadrats enthält. Dieser wird dann in einen WebGL FloatArray umgewandelt und durch die bufferData() Methode werden die Punkte für das Objekt festgelegt.

+ +

Die Szene zeichnen

+ +

Jetzt sind die Shader aufgebaut und das Objekt ist erstellt. Wir können die Szene rendern lassen. Da wir in dieser Szene nichts animieren, ist unsere drawScene() Funktion sehr einfach. Es werden einige nützliche Routinen verwendet, die wir uns kurz anschauen.

+ +
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);
+}
+
+ +

Als Erstes wird der Kontext auf unsere Hintergrundfarbe gesetzt und die Kameraperspektive festgelegt. Wir definieren ein Blickfeld von 45°, mit einem Höhen-/Breitenverhältnis von 640 zu 480 (die Größe unseres Canvas). Außerdem legen wir fest, dass wir nur Objekte zwischen 0.1 und 100 Einheiten gerendert haben wollen.

+ +

Dann wird die Position des Quadrats, über das Laden der ursprünglichen Position und der Verschiebung um 6 Einheiten von der Kamera weg, ermittelt. Danach, verbinden wir den Puffer des Quadrats mit dem Kontext, konfigurieren es, und zeichnen das Objekt, in dem wir die drawArrays() Methode aufrufen.

+ +

Das Ergebnis kann hier ausprobiert werden, wenn Sie einen Browser verwenden, der WebGL unterstützt.

+ +

Matrix Operationen

+ +

Matrix Operationen sind schon kompliziert genug. Keiner möchte wirklich den ganzen Code selbst schreiben, der benötigt wird um die Berechnungen selber durchzuführen. Glücklicherweise gibt es Sylvester, eine sehr handliche Bibliothek, die bestens mit Vektor und Matrix Operationen in JavaScript umgehen kann.

+ +

Die glUtils.js Datei, die in dieser Demo benutzt wird, wird bei einer ganzen Reihe von WebGL-Demos, die Web zu finden sind, verwendet. Keiner scheint sich völlig sicher zu sein, woher diese Bibliothek ursprünglich herkommt, aber es vereinfacht den Gebrauch von Sylvester noch weiter, in dem Methoden hinzugefügt werden, die auch spezielle Matrizentypen ermöglichen und HTML ausgegeben werden kann, um die Matrizen anzeigen zu lassen.

+ +

Zusätzlich, definiert diese Demo ein paar hilfreiche Routinen, um an diese Bibliothek für spezielle Aufgaben anzukoppeln. Was genau gemacht wird, ist kein Teil dieses Artikels, aber es gibt einige gute Referenzen zu Matrizen, die online verfügbar sind. Siehe unter Siehe auch, um ein paar aufzulisten.

+ +
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()));
+}
+
+ +

Siehe auch

+ + + +

{{PreviousNext("Web/API/WebGL_API/Tutorial/Einführung_in_WebGL", "Web/API/WebGL_API/Tutorial/Farben_mittels_Shader_in_einen_WebGL-Kontext_hinzufügen")}}

diff --git a/files/de/web/api/webgl_api/tutorial/index.html b/files/de/web/api/webgl_api/tutorial/index.html new file mode 100644 index 0000000000..34db3f57e6 --- /dev/null +++ b/files/de/web/api/webgl_api/tutorial/index.html @@ -0,0 +1,40 @@ +--- +title: WebGL Tutorial +slug: Web/API/WebGL_API/Tutorial +tags: + - Tutorial + - 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 diesem Tutorial

+ +
+
Einführung in WebGL
+
Wie man einen WebGL-Kontext herstellt.
+
Hinzufügen von 2D Inhalten in einen WebGL-Kontext
+
Wie eine einfache, flache Form mittels WebGL erstellt wird.
+
Farben mittels Shader in einen WebGL-Kontext hinzufügen
+
Zeigt wie Farben mit Shadern auf die Form gebracht werden können.
+
Objekte mit WebGL animieren
+
Erklärt wie Objekte rotiert und verschiebt werden, um eine einfache Animation zu erstellen.
+
3D-Objekte mit WebGL erstellen
+
Erläutert wie dreidimensionale Objekte erstellt und animiert werden (ein Würfel dient als Beispiel).
+
Texturen in WebGL verwenden
+
Demonstriert wie Texturen auf die Oberfläche eines Objektes gezeichnet werden können.
+
Beleuchtung in WebGL
+
Wie Beleuchtungseffekte in unserem WebGL-Kontext simuliert werden.
+
Animierte Texturen in WebGL
+
Animierte Texturen werden mittels einem Ogg-Video auf der Oberfläche eines rotierenden Würfels realisiert.
+
diff --git a/files/de/web/api/webgl_api/tutorial/objekte_mit_webgl_animieren/index.html b/files/de/web/api/webgl_api/tutorial/objekte_mit_webgl_animieren/index.html new file mode 100644 index 0000000000..a9eafed6db --- /dev/null +++ b/files/de/web/api/webgl_api/tutorial/objekte_mit_webgl_animieren/index.html @@ -0,0 +1,118 @@ +--- +title: Objekte mit WebGL animieren +slug: Web/API/WebGL_API/Tutorial/Objekte_mit_WebGL_animieren +tags: + - Tutorial + - WebGL +translation_of: Web/API/WebGL_API/Tutorial/Animating_objects_with_WebGL +--- +

{{WebGLSidebar("Tutorial")}} {{PreviousNext("Web/API/WebGL_API/Tutorial/Farben_mittels_Shader_in_einen_WebGL-Kontext_hinzufügen", "Web/API/WebGL_API/Tutorial/3D-Objekte_mit_WebGL_erstellen") }}

+ +

Unser Code vom vorherigen Beispiel ist bereits so konfiguriert, dass die WebGL-Szene alle 15 Millisekunden neu gezeichnet wird. Bis jetzt wird zu jeder Zeit das gleiche Bild immer neu gezeichnet. Das wollen wir nun ändern, sodass sich unser Quadrat auf der Bildfläche bewegt.

+ +

In diesem Beispiel rotieren und verschieben wir unser Quadrat in alle drei Dimensionen, sodass es schon in einem 3D Raum existieren kann (obwohl wir bisher nur ein 2D-Objekt erstellt haben).

+ +

Das Quadrat rotieren lassen

+ +

Fangen wir damit an, das Quadrat im Raum zu rotieren. Als erstes brauchen wir dazu eine Variable in welche wir die Rotation des Quadrats verfolgen können:

+ +
var squareRotation = 0.0;
+
+ +

Jetzt müssen wir die drawScene() Funktion ändern, um die aktuelle Rotation auf das Quadrat anzuwenden, wenn dies gezeichnet werden soll. Nach der Umrechnung der Startposition für das Quadrat, wenden wir eine Rotation wie diese an:

+ +
mvPushMatrix();
+mvRotate(squareRotation, [1, 0, 1]);
+
+ +

Das speichert die aktuelle Model-View Matrix und rotiert die Matrix mit dem aktuellen Wert von squareRotation um die X und Z Achsen.

+ +

Nach dem Zeichen müssen wir die Originalmatrix wiederherstellen:

+ +
mvPopMatrix();
+
+ +

Wir speichern und stellen die Originalmatrix dann wieder her, um zu verhindern, dass die Rotation auf andere Objekte angewendet wird, die wir vielleicht später noch zeichnen wollen.

+ +

Um letztendlich etwas zu animieren, brauchen wir noch ein paar Zeilen Code, welcher den Wert von squareRotation über die Zeit verändert. Dafür erstellen wir eine neue Variable, die die Zeit aufzeichnet, welche wir zuletzt animiert haben (wir nennen diese lastSquareUpdateTime), dann fügen wir den folgenden Code an das Ende der drawScene() Funktion:

+ +
var currentTime = (new Date).getTime();
+if (lastSquareUpdateTime) {
+  var delta = currentTime - lastSquareUpdateTime;
+  squareRotation += (30 * delta) / 1000.0;
+}
+lastSquareUpdateTime = currentTime;
+
+ +

Dieser Code benutzt den Betrag der Zeit, die vergangen ist, seitdem wir zum letzten Mal den Wert von squareRotation geändert haben, um festzustellen wie weit das Quadrat rotiert werden soll.

+ +

Das Quadrat bewegen

+ +

Wir können das Quadrat auch verschieben indem wir eine unterschiedliche Position berechnen lassen, bevor wir es zeichnen. Dieses Beispiel zeigt wie eine grundlegende Animation gemacht werden kann. Allerdings möchten Sie in einer echten Anwendung wohl eher etwas weniger Irrsinniges machen.

+ +

Verfolgen wir die Abstände zu jeder Achse für unsere Verschiebung in drei neuen Variablen:

+ +
var squareXOffset = 0.0;
+var squareYOffset = 0.0;
+var squareZOffset = 0.0;
+
+ +

Und den Betrag, welcher unsere Postion auf jeder Achse verändern soll, in diesen Variablen:

+ +
var xIncValue = 0.2;
+var yIncValue = -0.4;
+var zIncValue = 0.3;
+
+ +

Nun können wir einfach diesen Code zum vorherigen Code, der die Rotation aktualisiert, hinzufügen:

+ +
squareXOffset += xIncValue * ((30 * delta) / 1000.0);
+squareYOffset += yIncValue * ((30 * delta) / 1000.0);
+squareZOffset += zIncValue * ((30 * delta) / 1000.0);
+
+if (Math.abs(squareYOffset) > 2.5) {
+  xIncValue = -xIncValue;
+  yIncValue = -yIncValue;
+  zIncValue = -zIncValue;
+}
+
+ +

Das bringt unser Quadrat dazu seine Größe zu verändern, sich willkürlich auf der Fläche zu verschieben, sich vom Betrachter weg und zum Betrachter hin zu bewegen und das alles während das Quadrat auch noch rotiert. Das sieht dann schon eher wie ein Bildschirmschoner aus.

+ +

Wenn Ihr Browser WebGL unterstützt, ist hier das Beispiel in Aktion.

+ +

Weitere Matrixoperationen

+ +

Dieses Beispiel verwendet einige zusätzliche Matrixoperationen, darunter zwei Routinen, die die Matrizen verschieben, wiederherstellen und in einem Stack aufbewahren und eine Routine, die die Matrix um eine gewissen Anzahl von Grad rotiert:

+ +
var mvMatrixStack = [];
+
+function mvPushMatrix(m) {
+  if (m) {
+    mvMatrixStack.push(m.dup());
+    mvMatrix = m.dup();
+  } else {
+    mvMatrixStack.push(mvMatrix.dup());
+  }
+}
+
+function mvPopMatrix() {
+  if (!mvMatrixStack.length) {
+    throw("Can't pop from an empty matrix stack.");
+  }
+
+  mvMatrix = mvMatrixStack.pop();
+  return mvMatrix;
+}
+
+function mvRotate(angle, v) {
+  var inRadians = angle * Math.PI / 180.0;
+
+  var m = Matrix.Rotation(inRadians, $V([v[0], v[1], v[2]])).ensure4x4();
+  multMatrix(m);
+}
+
+ +

Diese Routinen wurden von einem Beispiel ausgeliehen, welches von Vlad Vukićević geschrieben wurde.

+ +

{{PreviousNext("Web/API/WebGL_API/Tutorial/Farben_mittels_Shader_in_einen_WebGL-Kontext_hinzufügen", "Web/API/WebGL_API/Tutorial/3D-Objekte_mit_WebGL_erstellen") }}

diff --git a/files/de/web/api/webgl_api/tutorial/texturen_in_webgl_verwenden/index.html b/files/de/web/api/webgl_api/tutorial/texturen_in_webgl_verwenden/index.html new file mode 100644 index 0000000000..eb59417694 --- /dev/null +++ b/files/de/web/api/webgl_api/tutorial/texturen_in_webgl_verwenden/index.html @@ -0,0 +1,159 @@ +--- +title: Texturen in WebGL verwenden +slug: Web/API/WebGL_API/Tutorial/Texturen_in_WebGL_verwenden +tags: + - Tutorial + - WebGL +translation_of: Web/API/WebGL_API/Tutorial/Using_textures_in_WebGL +--- +

{{WebGLSidebar("Tutorial")}} {{PreviousNext("Web/API/WebGL_API/Tutorial/3D-Objekte_mit_WebGL_erstellen", "Web/API/WebGL_API/Tutorial/Beleuchtung_in_WebGL")}}

+ +

Jetzt wo unser Beispielprogramm über einen rotierenden 3D-Würfel verfügt, wollen wir darauf eine Textur legen, statt der bisher verwendeten, einfachen Farben.

+ +

Texturen laden

+ +

Als Erstes müssen wir ein paar Zeilen Code hinzufügen, um die Texturen zu laden. In unserem Fall werden wir eine einzige Textur verwenden, die auf alle sechs Seiten des rotierenden Würfels gelegt wird, aber die gleiche Technik kann verwendet werden, um jede beliebig viele Texturen auf ein Objekt zu legen.

+ +

Der Code, der die Textur lädt, sieht so aus:

+ +
function initTextures() {
+  gl.enable(gl.TEXTURE_2D);
+  cubeTexture = gl.createTexture();
+  cubeImage = new Image();
+  cubeImage.onload = function() { handleTextureLoaded(cubeImage, cubeTexture); }
+  cubeImage.src = "cubetexture.png";
+}
+
+function handleTextureLoaded(image, texture) {
+  gl.bindTexture(gl.TEXTURE_2D, texture);
+  gl.texImage2D(gl.TEXTURE_2D, 0, image, true);
+  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
+  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_NEAREST);
+  gl.generateMipmap(gl.TEXTURE_2D);
+  gl.bindTexture(gl.TEXTURE_2D, null);
+}
+
+ +

Die Routine initTextures() aktiviert zunächst die Unterstützung von Texturen, dann wird das GL Textur-Objekt cubeTexture durch Aufruf der GL createTexture() Funktion erstellt. Um die Textur von der Bilddatei zu laden, wird dann ein Image-Objekt erstellt und in die Grafikdatei geladen, die wir als unsere Textur verwenden wollen. Die handleTextureLoaded() Callback-Routine wird ausgeführt, wenn das Bild geladen wurde.

+ +

Um schließlich die Textur zu erstellen, legen wir fest, dass die neue Textur die aktuelle Textur ist, mit welcher wir arbeiten wollen und verbinden diese mit gl.TEXTURE_2D. Danach wird das geladene Bild mit texImage2D() die Bilddaten in die Textur schreiben.

+ +

Die nächsten zwei Zeilen legen Filter für die Textur fest, die steuern, wie das Bild gefiltert wird, wenn es skaliert wird. In diesem Fall verwenden wir lineare Filter, wenn das Bild hoch skaliert wird und Mip-Mapping wenn wir herunter skalieren. Dann wird die Mip-Map generiert, indem generateMipMap() aufgerufen wird. Schließlich teilen wir WebGL mit, dass wir mit der Arbeit an der Textur fertig sind, in dem wir null mit gl.TEXTURE_2D verknüpfen.

+ +

Textur auf die Flächen legen

+ +

Nun ist die Textur geladen und bereit eingesetzt zu werden. Bevor wir die Textur aber verwenden können, müssen wir die Texturkoordinaten auf die Vertices der Flächen des Würfels legen. Das ersetzt den vorherigen Code in initBuffers(), der die Farben für jede Fläche festgelegt hat.

+ +
  cubeVerticesTextureCoordBuffer = gl.createBuffer();
+  gl.bindBuffer(gl.ARRAY_BUFFER, cubeVerticesTextureCoordBuffer);
+
+  var textureCoordinates = [
+    // vorne
+    0.0,  0.0,
+    1.0,  0.0,
+    1.0,  1.0,
+    0.0,  1.0,
+    // hinten
+    0.0,  0.0,
+    1.0,  0.0,
+    1.0,  1.0,
+    0.0,  1.0,
+    // oben
+    0.0,  0.0,
+    1.0,  0.0,
+    1.0,  1.0,
+    0.0,  1.0,
+    // unten
+    0.0,  0.0,
+    1.0,  0.0,
+    1.0,  1.0,
+    0.0,  1.0,
+    // rechts
+    0.0,  0.0,
+    1.0,  0.0,
+    1.0,  1.0,
+    0.0,  1.0,
+    // links
+    0.0,  0.0,
+    1.0,  0.0,
+    1.0,  1.0,
+    0.0,  1.0
+  ];
+
+  gl.bufferData(gl.ARRAY_BUFFER, new WebGLFloatArray(textureCoordinates),
+                gl.STATIC_DRAW);
+
+ +

Zuerst erstellt dieser Code einen GL-Buffer in welchen wir die Texturkoordinaten für jede Fläche speichern werden, dann verknüpfen wir diesen Buffer als das Array in welchen wir schreiben werden.

+ +

Das textureCoordinates Array definiert die Texturkoordinaten entsprechend jedem Vertex von jeder Fläche. Beachten Sie, dass die Texturkoordinaten sich im Bereich von 0.0 bis 1.0 befinden. Beim Texturmapping werden die Dimensionen von Texturen immer auf einen Bereich von 0.0 bis 1.0 normiert, egal welche Größe die Textur wirklich hat.

+ +

Sobald wir das Texturmapping-Array erstellt haben, speichern wir das Array in den Buffer, sodass GL die Daten zur Verfügung hat.

+ +

Die Shader aktualisieren

+ +

Das Shader-Programm - und der Code, der die Shader initialisiert - muss aktualisiert werden, damit die Textur anstatt der Farben verwendet wird.

+ +

Werfen wir zunächst einen Blick auf die einfache Änderung, die in initShaders() benötigt wird:

+ +
  textureCoordAttribute = gl.getAttribLocation(shaderProgram, "aTextureCoord");
+  gl.enableVertexAttribArray(textureCoordAttribute);
+
+ +

Das ersetzt den Code, der die Vertex Farbattribute enthielt, mit dem, der nun die Texturkoordinaten für jeden Vertex enthält.

+ +

Der Vertex-Shader

+ +

Als Nächstes müssen wir den Vertex-Shader ersetzen, sodass statt der Farbdaten die Texturkoordinaten abgerufen werden.

+ +
    <script id="shader-vs" type="x-shader/x-vertex">
+      attribute vec3 aVertexPosition;
+      attribute vec2 aTextureCoord;
+
+      uniform mat4 uMVMatrix;
+      uniform mat4 uPMatrix;
+
+      varying vec2 vTextureCoord;
+
+      void main(void) {
+        gl_Position = uPMatrix * uMVMatrix * vec4(aVertexPosition, 1.0);
+        vTextureCoord = aTextureCoord;
+      }
+    </script>
+
+ +

Die wichtigste Änderung ist hier, dass anstatt die Vertex-Farbe abzurufen, die Texturkoordinaten gesetzt werden. Das gibt den Ort der Textur entsprechend zum Vertex an.

+ +

Der Fragment-Shader

+ +

Der Fragment-Shader muss in ähnlicher Weise geändert werden:

+ +
    <script id="shader-fs" type="x-shader/x-fragment">
+      varying vec2 vTextureCoord;
+
+      uniform sampler2D uSampler;
+
+      void main(void) {
+        gl_FragColor = texture2D(uSampler, vec2(vTextureCoord.s, vTextureCoord.t));
+      }
+    </script>
+
+ +

Anstatt einen Farbwert auf die Fragment-Farbe zu legen, wird die Fragment-Farbe berechnet in dem der texel (der Pixel innerhalb der Textur) abgerufen wird, der am Besten auf die Fragement-Position laut dem Sampler passt.

+ +

Zeichnen des textuierten Würfels

+ +

Die Änderungen an der drawScene() Funktion sind einfach (mit der Ausnahme, dass ich nun zur besseren Anschaulichkeit die Verschiebungen entfernt habe und der Würfel nur noch rotiert wird).

+ +

Der Code, der die Farben auf die Textur legt ist weg und wurde ersetzt:

+ +
  gl.activeTexture(gl.TEXTURE0);
+  gl.bindTexture(gl.TEXTURE_2D, cubeTexture);
+  gl.uniform1i(gl.getUniformLocation(shaderProgram, "uSampler"), 0);
+
+ +

GL ermöglicht 32 Textur-Register; der Erste davon ist gl.TEXTURE0. Wir verknüpfen unsere geladene Textur zu diesem Register, dann wird der Shader-Sampler uSampler gesetzt (im Shader-Program festgelegt), um die Textur zu benutzen.

+ +

Jetzt sollte der rotierende Würfel gut anzuschauen zu sein. Wenn Ihr Browser WebGL unterstützt, können Sie das Live-Beispiel ausprobieren.

+ +

{{PreviousNext("Web/API/WebGL_API/Tutorial/3D-Objekte_mit_WebGL_erstellen", "Web/API/WebGL_API/Tutorial/Beleuchtung_in_WebGL")}}

diff --git a/files/de/web/api/webglactiveinfo/index.html b/files/de/web/api/webglactiveinfo/index.html new file mode 100644 index 0000000000..ed46e4e058 --- /dev/null +++ b/files/de/web/api/webglactiveinfo/index.html @@ -0,0 +1,129 @@ +--- +title: WebGLActiveInfo +slug: Web/API/WebGLActiveInfo +translation_of: Web/API/WebGLActiveInfo +--- +
{{APIRef("WebGL")}}
+ +

Das WebGLActiveInfo-Interface ist Teil der WebGL API und repräsentiert die Informationen der Rückgabewerte von den {{domxref("WebGLRenderingContext.getActiveAttrib()")}} und {{domxref("WebGLRenderingContext.getActiveUniform()")}} Methoden.

+ +

Eigenschaften

+ +
+
{{domxref("WebGLActiveInfo.name")}}
+
Der schreibgeschützte Name von der abgefragten Variable
+
{{domxref("WebGLActiveInfo.size")}}
+
Die schreibgeschützte Größe der abgefragten Variable
+
{{domxref("WebGLActiveInfo.type")}}
+
Der schreibgeschützte Typ der abgefragten Variable
+
+ +

Beispiele

+ +

Ein WebGLActiveInfo-Objekt wird von den folgenden Funktionen zurück gegeben:

+ + + +
WebGLActiveInfo? getActiveAttrib(WebGLProgram? program, GLuint index);
+WebGLActiveInfo? getActiveUniform(WebGLProgram? program, GLuint index);
+WebGLActiveInfo? getTransformFeedbackVarying(WebGLProgram? program, GLuint index)
+
+ +

Spezifikationen

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WebGL', "#5.11", "WebGLActiveInfo")}}{{Spec2('WebGL')}}Erstmalige Definition
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome("9")}}{{CompatGeckoDesktop("2.0")}}{{CompatIE("11")}}{{CompatOpera("12")}}{{CompatSafari("5.1")}}
Available in workers{{CompatNo}}{{CompatGeckoDesktop(44)}} [1]{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}25{{CompatVersionUnknown}}{{CompatUnknown}}128.1
Available in workers{{CompatNo}}{{CompatNo}}{{CompatGeckoMobile(44)}} [1]{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

[1] Dieses Feature ist durch eine Voreinstellung deaktiviert. Zur Aktivierung setzt man in about:config den Wert gfx.offscreencanvas.enabled auf true.

+ +

See also

+ + diff --git a/files/de/web/api/webglprogram/index.html b/files/de/web/api/webglprogram/index.html new file mode 100644 index 0000000000..3d115b5947 --- /dev/null +++ b/files/de/web/api/webglprogram/index.html @@ -0,0 +1,166 @@ +--- +title: WebGLProgram +slug: Web/API/WebGLProgram +tags: + - WebGL + - WebGLProgram +translation_of: Web/API/WebGLProgram +--- +
{{APIRef("WebGL")}}
+ +

Das WebGLProgram ist ein Teil der WebGL API und ist eine Kombination aus zwei kompilierten {{domxref("WebGLShader")}}n, bestehend aus einem Vertex-Shader und einem Fragment-Shader (beide in GLSL geschrieben). Diese werden dann zu einem benutzbaren Programm zusammen gelinkt.

+ +
var program = gl.createProgram();
+
+// Bereits existierende Shader hinzufügen
+gl.attachShader(program, vertexShader);
+gl.attachShader(program, fragmentShader);
+
+gl.linkProgram(program);
+
+if ( !gl.getProgramParameter( program, gl.LINK_STATUS) ) {
+  var info = gl.getProgramInfoLog(program);
+  throw "WebGL-Programm konnte nicht kompiliert werden. \n\n" + info;
+}
+
+ +

Für weitere Informationen über das Erstellen von vertexShader und fragmentShader, lese dir {{domxref("WebGLShader")}} durch.

+ +

Beispiele

+ +

Das Program benutzen

+ +

Hier wird zu erst der GPU mit geteilt, dass sie das Programm benutzen soll. Danach werden die benötigten Daten und Konfigurationen vorgenommen und zuletzt wird etwas auf den Bildschirm gezeichnet.

+ +
// Das Programm benutzen
+gl.useProgram(program);
+
+// Bereits existierende Attribute binden
+gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
+gl.enableVertexAttribArray(attributeLocation);
+gl.vertexAttribPointer(attributeLocation, 3, gl.FLOAT, false, 0, 0);
+
+// Ein einzelnes Dreieck zeichnen
+gl.drawArrays(gl.TRIANGLES, 0, 3);
+
+ +

Das Programm löschen

+ +

Falls es bei dem Linken des Programms zu fehlern kommt oder falls du ein bereits erstelltes Programm einfach nur löschen möchtest, dann kannst du einfach {{domxref("WebGLRenderingContext.deleteProgram()")}} ausführen. Dies löscht den Speicher des gelinkten Programms.

+ +
gl.deleteProgram(program);
+
+ +

Spezifikationen

+ + + + + + + + + + + + + + +
SpezifikationStatusKommentar
{{SpecName('WebGL', "#5.6", "WebGLProgram")}}{{Spec2('WebGL')}}Erstmalige Definition
+ +

Browser-Kompatibilität

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome("9")}}{{CompatGeckoDesktop("2.0")}}{{CompatIE("11")}}{{CompatOpera("12")}}{{CompatSafari("5.1")}}
Available in workers{{CompatNo}}{{CompatGeckoDesktop(44)}} [1]{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}25{{CompatVersionUnknown}}{{CompatUnknown}}128.1
Available in workers{{CompatNo}}{{CompatNo}}{{CompatGeckoMobile(44)}} [1]{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

[1] This feature is behind a feature preference setting. In about:config, set gfx.offscreencanvas.enabled to true.

+ +

Weiterführendes

+ + diff --git a/files/de/web/api/webglrenderingcontext/canvas/index.html b/files/de/web/api/webglrenderingcontext/canvas/index.html new file mode 100644 index 0000000000..4f54fd191e --- /dev/null +++ b/files/de/web/api/webglrenderingcontext/canvas/index.html @@ -0,0 +1,74 @@ +--- +title: WebGLRenderingContext.canvas +slug: Web/API/WebGLRenderingContext/canvas +tags: + - Schreibgeschützt + - WebGL + - WebGLRenderingContext +translation_of: Web/API/WebGLRenderingContext/canvas +--- +
{{APIRef("WebGL")}}
+ +

Die Eigenschaft WebGLRenderingContext.canvas ist eine schreibgeschütze Referenz auf das {{domxref("HTMLCanvasElement")}} oder das {{domxref("OffscreenCanvas")}} Objekt, welches mit dem Context verknüpft ist. Es kann auch den Wert {{jsxref("null")}} annehmen, wenn es keinem {{HTMLElement("canvas")}} Element oder {{domxref("OffscreenCanvas")}} Objekt zugeordnet ist.

+ +

Syntax

+ +
gl.canvas;
+ +

Rückgabewert

+ +

Entweder ein {{domxref("HTMLCanvasElement")}}, ein {{domxref("OffscreenCanvas")}} Objekt oder {{jsxref("null")}}.

+ +

Beispiele

+ +

Canvas Element

+ +

Gegeben ist ein {{HTMLElement("canvas")}} Element:

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

Du kannst die Eigenschaft canvas aus dem WebGLRenderingContext auslesen um eine Referenz darauf zu erhalten.

+ +
var canvas = document.getElementById('canvas');
+var gl = canvas.getContext('webgl');
+gl.canvas; // HTMLCanvasElement
+
+ +

Offscreen Canvas

+ +

Beispiel des experimentellen {{domxref("OffscreenCanvas")}} Objektes.

+ +
var offscreen = new OffscreenCanvas(256, 256);
+var gl = offscreen.getContext('webgl');
+gl.canvas; // OffscreenCanvas
+ +

Spezifikationen

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WebGL', "#DOM-WebGLRenderingContext-canvas", "WebGLRenderingContext.canvas")}}{{Spec2('WebGL')}}Ursprüngliche Definition.
+ +

Browserkompatibilität

+ + + +

{{Compat("api.WebGLRenderingContext.canvas")}}

+ +

Siehe auch

+ + diff --git a/files/de/web/api/webglrenderingcontext/getactiveattrib/index.html b/files/de/web/api/webglrenderingcontext/getactiveattrib/index.html new file mode 100644 index 0000000000..0774b87631 --- /dev/null +++ b/files/de/web/api/webglrenderingcontext/getactiveattrib/index.html @@ -0,0 +1,115 @@ +--- +title: WebGLRenderingContext.getActiveAttrib() +slug: Web/API/WebGLRenderingContext/getActiveAttrib +translation_of: Web/API/WebGLRenderingContext/getActiveAttrib +--- +
{{APIRef("WebGL")}}
+ +

Die WebGLRenderingContext.getActiveAttrib() Methode der WebGL API gibt ein {{domxref("WebGLActiveInfo")}} Objekt zurück, welches die Größe, den Typ und den Namen eines Vertex-Attributes an der gegebenen Position in einem {{domxref("WebGLProgram")}} enthält.

+ +

Syntax

+ +
WebGLActiveInfo gl.getActiveAttrib(program,index);
+
+ +

Parameter

+ +
+
program
+
Ein {{domxref("WebGLProgram")}}, welches das Vertex-Attribut enthält
+
index
+
Ein {{domxref("GLuint")}}, welcher den Index des Vertex-Attributes angibt
+
+ +

Rückgabewert

+ +

Ein {{domxref("WebGLActiveInfo")}} Objekt.

+ +

Beispiele

+ +
gl.getActiveAttrib(program, i);
+
+ +

Spezifikationen

+ + + + + + + + + + + + + + + + + + + +
SpezifikationStatusKommentar
{{SpecName('WebGL', "#5.14.10", "getActiveAttrib")}}{{Spec2('WebGL')}}Erstmalige Definition
{{SpecName('OpenGL ES 2.0', "glGetActiveAttrib.xml", "glGetActiveAttrib")}}{{Spec2('OpenGL ES 2.0')}}Man page der OpenGL API
+ +

Browser-Kompatibilität

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome("9")}}12{{CompatGeckoDesktop("2.0")}}11{{CompatOpera("12")}}{{CompatSafari("5.1")}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}25{{CompatGeckoMobile("2.0")}}1.0{{CompatUnknown}}128.0
+
+ +

Weiterführendes

+ + diff --git a/files/de/web/api/webglrenderingcontext/getattriblocation/index.html b/files/de/web/api/webglrenderingcontext/getattriblocation/index.html new file mode 100644 index 0000000000..7088f72b90 --- /dev/null +++ b/files/de/web/api/webglrenderingcontext/getattriblocation/index.html @@ -0,0 +1,65 @@ +--- +title: WebGLRenderingContext.getAttribLocation() +slug: Web/API/WebGLRenderingContext/getAttribLocation +translation_of: Web/API/WebGLRenderingContext/getAttribLocation +--- +
{{APIRef("WebGL")}}
+ +

Die Methode WebGLRenderingContext.getAttribLocation() aus der WebGL API gibt die Position einer At­tri­but Variable innerhalb eines gegebenen {{domxref("WebGLProgram")}} zurück.

+ +

Syntax

+ +
GLint gl.getAttribLocation(program, name);
+
+ +

Parameter

+ +
+
program
+
Ein {{domxref("WebGLProgram")}} das die At­tri­but Variable enthält.
+
name
+
Ein {{domxref("DOMString")}} der den Namen des Attributes angibt, dessen Position gesucht wird.
+
+ +

Rückgabewert

+ +

Wenn gefunden, wird die Position der Variable als {{domxref("GLint")}}, andernfalls -1 zurückgegeben.

+ +

Beispiele

+ +
gl.getAttribLocation(program, 'vColor');
+
+ +

Spezifikationen

+ + + + + + + + + + + + + + + + + + + +
SpezifikationStatusKommentar
{{SpecName('WebGL', "#5.14.10", "getAttribLocation")}}{{Spec2('WebGL')}}Ursprüngliche Definition.
{{SpecName('OpenGL ES 2.0', "glGetAttribLocation.xml", "glGetAttribLocation")}}{{Spec2('OpenGL ES 2.0')}}Hauptseite der OpenGL API.
+ +

Browserkompatibilität

+ + + +

{{Compat("api.WebGLRenderingContext.getAttribLocation")}}

+ +

Siehe auch

+ + diff --git a/files/de/web/api/webglrenderingcontext/index.html b/files/de/web/api/webglrenderingcontext/index.html new file mode 100644 index 0000000000..77182a3177 --- /dev/null +++ b/files/de/web/api/webglrenderingcontext/index.html @@ -0,0 +1,441 @@ +--- +title: WebGLRenderingContext +slug: Web/API/WebGLRenderingContext +tags: + - NeedsTranslation + - TopicStub + - WebGL + - WebGLRenderingContext +translation_of: Web/API/WebGLRenderingContext +--- +
{{APIRef("WebGL")}}
+ +

The WebGLRenderingContext interface provides the OpenGL ES 2.0 rendering context for the drawing surface of an HTML {{HTMLElement("canvas")}} element.

+ +

To get an object of this interface, call {{domxref("HTMLCanvasElement.getContext()", "getContext()")}} on a <canvas> element, supplying "webgl" as the argument:

+ +
var canvas = document.getElementById('myCanvas');
+var gl = canvas.getContext('webgl');
+
+ +

Once you have the WebGL rendering context for a canvas, you can render within it.

+ +

The WebGL tutorial has more information, examples, and resources on how to get started with WebGL.

+ +

Constants

+ +

See the WebGL constants page.

+ +

The WebGL context

+ +

The following properties and methods provide general information and functionality to deal with the WebGL context:

+ +
+
{{domxref("WebGLRenderingContext.canvas")}}
+
A read-only back-reference to the {{domxref("HTMLCanvasElement")}}. Might be {{jsxref("null")}} if it is not associated with a {{HTMLElement("canvas")}} element.
+
{{domxref("WebGLRenderingContext.commit()")}} {{experimental_inline}}
+
+

Pushes frames back to the original {{domxref("HTMLCanvasElement")}}, if the context is not directly fixed to a specific canvas.

+
+
{{domxref("WebGLRenderingContext.drawingBufferWidth")}}
+
The read-only width of the current drawing buffer. Should match the width of the canvas element associated with this context.
+
{{domxref("WebGLRenderingContext.drawingBufferHeight")}}
+
The read-only height of the current drawing buffer. Should match the height of the canvas element associated with this context.
+
{{domxref("WebGLRenderingContext.getContextAttributes()")}}
+
Returns a WebGLContextAttributes object that contains the actual context parameters. Might return {{jsxref("null")}}, if the context is lost.
+
{{domxref("WebGLRenderingContext.isContextLost()")}}
+
Returns true if the context is lost, otherwise returns false.
+
+ +

Viewing and clipping

+ +
+
{{domxref("WebGLRenderingContext.scissor()")}}
+
Defines the scissor box.
+
{{domxref("WebGLRenderingContext.viewport()")}}
+
Sets the viewport.
+
+ +

State information

+ +
+
{{domxref("WebGLRenderingContext.activeTexture()")}}
+
Selects the active texture unit.
+
{{domxref("WebGLRenderingContext.blendColor()")}}
+
Sets the source and destination blending factors.
+
{{domxref("WebGLRenderingContext.blendEquation()")}}
+
Sets both the RGB blend equation and alpha blend equation to a single equation.
+
{{domxref("WebGLRenderingContext.blendEquationSeparate()")}}
+
Sets the RGB blend equation and alpha blend equation separately.
+
{{domxref("WebGLRenderingContext.blendFunc()")}}
+
Defines which function is used for blending pixel arithmetic.
+
{{domxref("WebGLRenderingContext.blendFuncSeparate()")}}
+
Defines which function is used for blending pixel arithmetic for RGB and alpha components separately.
+
{{domxref("WebGLRenderingContext.clearColor()")}}
+
Specifies the color values used when clearing color buffers.
+
{{domxref("WebGLRenderingContext.clearDepth()")}}
+
Specifies the depth value used when clearing the depth buffer.
+
{{domxref("WebGLRenderingContext.clearStencil()")}}
+
Specifies the stencil value used when clearing the stencil buffer.
+
{{domxref("WebGLRenderingContext.colorMask()")}}
+
Sets which color components to enable or to disable when drawing or rendering to a {{domxref("WebGLFramebuffer")}}.
+
{{domxref("WebGLRenderingContext.cullFace()")}}
+
Specifies whether or not front- and/or back-facing polygons can be culled.
+
{{domxref("WebGLRenderingContext.depthFunc()")}}
+
Specifies a function that compares incoming pixel depth to the current depth buffer value.
+
{{domxref("WebGLRenderingContext.depthMask()")}}
+
Sets whether writing into the depth buffer is enabled or disabled.
+
{{domxref("WebGLRenderingContext.depthRange()")}}
+
Specifies the depth range mapping from normalized device coordinates to window or viewport coordinates.
+
{{domxref("WebGLRenderingContext.disable()")}}
+
Disables specific WebGL capabilities for this context.
+
{{domxref("WebGLRenderingContext.enable()")}}
+
Enables specific WebGL capabilities for this context.
+
{{domxref("WebGLRenderingContext.frontFace()")}}
+
Specifies whether polygons are front- or back-facing by setting a winding orientation.
+
{{domxref("WebGLRenderingContext.getParameter()")}}
+
Returns a value for the passed parameter name.
+
{{domxref("WebGLRenderingContext.getError()")}}
+
Returns error information.
+
{{domxref("WebGLRenderingContext.hint()")}}
+
Specifies hints for certain behaviors. The interpretation of these hints depend on the implementation.
+
{{domxref("WebGLRenderingContext.isEnabled()")}}
+
Tests whether a specific WebGL capability is enabled or not for this context.
+
{{domxref("WebGLRenderingContext.lineWidth()")}}
+
Sets the line width of rasterized lines.
+
{{domxref("WebGLRenderingContext.pixelStorei()")}}
+
Specifies the pixel storage modes
+
{{domxref("WebGLRenderingContext.polygonOffset()")}}
+
Specifies the scale factors and units to calculate depth values.
+
{{domxref("WebGLRenderingContext.sampleCoverage()")}}
+
Specifies multi-sample coverage parameters for anti-aliasing effects.
+
{{domxref("WebGLRenderingContext.stencilFunc()")}}
+
Sets the both front and back function and reference value for stencil testing.
+
{{domxref("WebGLRenderingContext.stencilFuncSeparate()")}}
+
Sets the front and/or back function and reference value for stencil testing.
+
{{domxref("WebGLRenderingContext.stencilMask()")}}
+
Controls enabling and disabling of both the front and back writing of individual bits in the stencil planes.
+
{{domxref("WebGLRenderingContext.stencilMaskSeparate()")}}
+
Controls enabling and disabling of front and/or back writing of individual bits in the stencil planes.
+
{{domxref("WebGLRenderingContext.stencilOp()")}}
+
Sets both the front and back-facing stencil test actions.
+
{{domxref("WebGLRenderingContext.stencilOpSeparate()")}}
+
Sets the front and/or back-facing stencil test actions.
+
+ +

Buffers

+ +
+
{{domxref("WebGLRenderingContext.bindBuffer()")}}
+
Binds a WebGLBuffer object to a given target.
+
{{domxref("WebGLRenderingContext.bufferData()")}}
+
Updates buffer data.
+
{{domxref("WebGLRenderingContext.bufferSubData()")}}
+
Updates buffer data starting at a passed offset.
+
{{domxref("WebGLRenderingContext.createBuffer()")}}
+
Creates a WebGLBuffer object.
+
{{domxref("WebGLRenderingContext.deleteBuffer()")}}
+
Deletes a WebGLBuffer object.
+
{{domxref("WebGLRenderingContext.getBufferParameter()")}}
+
Returns information about the buffer.
+
{{domxref("WebGLRenderingContext.isBuffer()")}}
+
Returns a Boolean indicating if the passed buffer is valid.
+
+ +

Framebuffers

+ +
+
{{domxref("WebGLRenderingContext.bindFramebuffer()")}}
+
Binds a WebGLFrameBuffer object to a given target.
+
{{domxref("WebGLRenderingContext.checkFramebufferStatus()")}}
+
Returns the status of the framebuffer.
+
{{domxref("WebGLRenderingContext.createFramebuffer()")}}
+
Creates a WebGLFrameBuffer object.
+
{{domxref("WebGLRenderingContext.deleteFramebuffer()")}}
+
Deletes a WebGLFrameBuffer object.
+
{{domxref("WebGLRenderingContext.framebufferRenderbuffer()")}}
+
Attaches a WebGLRenderingBuffer object to a WebGLFrameBuffer object.
+
{{domxref("WebGLRenderingContext.framebufferTexture2D()")}}
+
Attaches a textures image to a WebGLFrameBuffer object.
+
{{domxref("WebGLRenderingContext.getFramebufferAttachmentParameter()")}}
+
Returns information about the framebuffer.
+
{{domxref("WebGLRenderingContext.isFramebuffer()")}}
+
Returns a Boolean indicating if the passed WebGLFrameBuffer object is valid.
+
{{domxref("WebGLRenderingContext.readPixels()")}}
+
Reads a block of pixels from the WebGLFrameBuffer.
+
+ +

Renderbuffers

+ +
+
{{domxref("WebGLRenderingContext.bindRenderbuffer()")}}
+
Binds a WebGLRenderBuffer object to a given target.
+
{{domxref("WebGLRenderingContext.createRenderbuffer()")}}
+
Creates a WebGLRenderBuffer object.
+
{{domxref("WebGLRenderingContext.deleteRenderbuffer()")}}
+
Deletes a WebGLRenderBuffer object.
+
{{domxref("WebGLRenderingContext.getRenderbufferParameter()")}}
+
Returns information about the renderbuffer.
+
{{domxref("WebGLRenderingContext.isRenderbuffer()")}}
+
Returns a Boolean indicating if the passed WebGLRenderingBuffer is valid.
+
{{domxref("WebGLRenderingContext.renderbufferStorage()")}}
+
Creates a renderbuffer data store.
+
+ +

Textures

+ +
+
{{domxref("WebGLRenderingContext.bindTexture()")}}
+
Binds a WebGLTexture object to a given target.
+
{{domxref("WebGLRenderingContext.compressedTexImage2D()")}}
+
Specifies a 2D texture image in a compressed format.
+
{{domxref("WebGLRenderingContext.compressedTexSubImage2D()")}}
+
Specifies a 2D texture sub-image in a compressed format.
+
{{domxref("WebGLRenderingContext.copyTexImage2D()")}}
+
Copies a 2D texture image.
+
{{domxref("WebGLRenderingContext.copyTexSubImage2D()")}}
+
Copies a 2D texture sub-image.
+
{{domxref("WebGLRenderingContext.createTexture()")}}
+
Creates a WebGLTexture object.
+
{{domxref("WebGLRenderingContext.deleteTexture()")}}
+
Deletes a WebGLTexture object.
+
{{domxref("WebGLRenderingContext.generateMipmap()")}}
+
Generates a set of mipmaps for a WebGLTexture object.
+
{{domxref("WebGLRenderingContext.getTexParameter()")}}
+
Returns information about the texture.
+
{{domxref("WebGLRenderingContext.isTexture()")}}
+
Returns a Boolean indicating if the passed WebGLTexture is valid.
+
{{domxref("WebGLRenderingContext.texImage2D()")}}
+
Specifies a 2D texture image.
+
{{domxref("WebGLRenderingContext.texSubImage2D()")}}
+
Updates a sub-rectangle of the current WebGLTexture.
+
{{domxref("WebGLRenderingContext.texParameter", "WebGLRenderingContext.texParameterf()")}}
+
Sets texture parameters.
+
{{domxref("WebGLRenderingContext.texParameter", "WebGLRenderingContext.texParameteri()")}}
+
Sets texture parameters.
+
+ +

Programs and shaders

+ +
+
{{domxref("WebGLRenderingContext.attachShader()")}}
+
Attaches a WebGLShader to a WebGLProgram.
+
{{domxref("WebGLRenderingContext.bindAttribLocation()")}}
+
Binds a generic vertex index to a named attribute variable.
+
{{domxref("WebGLRenderingContext.compileShader()")}}
+
Compiles a WebGLShader.
+
{{domxref("WebGLRenderingContext.createProgram()")}}
+
Creates a WebGLProgram.
+
{{domxref("WebGLRenderingContext.createShader()")}}
+
Creates a WebGLShader.
+
{{domxref("WebGLRenderingContext.deleteProgram()")}}
+
Deletes a WebGLProgram.
+
{{domxref("WebGLRenderingContext.deleteShader()")}}
+
Deletes a WebGLShader.
+
{{domxref("WebGLRenderingContext.detachShader()")}}
+
Detaches a WebGLShader.
+
{{domxref("WebGLRenderingContext.getAttachedShaders()")}}
+
Returns a list of WebGLShader objects attached to a WebGLProgram.
+
{{domxref("WebGLRenderingContext.getProgramParameter()")}}
+
Returns information about the program.
+
{{domxref("WebGLRenderingContext.getProgramInfoLog()")}}
+
Returns the information log for a WebGLProgram object.
+
{{domxref("WebGLRenderingContext.getShaderParameter()")}}
+
Returns information about the shader.
+
{{domxref("WebGLRenderingContext.getShaderPrecisionFormat()")}}
+
Returns a WebGLShaderPrecisionFormat object describing the precision for the numeric format of the shader.
+
{{domxref("WebGLRenderingContext.getShaderInfoLog()")}}
+
Returns the information log for a WebGLShader object.
+
{{domxref("WebGLRenderingContext.getShaderSource()")}}
+
Returns the source code of a WebGLShader as a string.
+
{{domxref("WebGLRenderingContext.isProgram()")}}
+
Returns a Boolean indicating if the passed WebGLProgram is valid.
+
{{domxref("WebGLRenderingContext.isShader()")}}
+
Returns a Boolean indicating if the passed WebGLShader is valid.
+
{{domxref("WebGLRenderingContext.linkProgram()")}}
+
Links the passed WebGLProgram object.
+
{{domxref("WebGLRenderingContext.shaderSource()")}}
+
Sets the source code in a WebGLShader.
+
{{domxref("WebGLRenderingContext.useProgram()")}}
+
Uses the specified WebGLProgram as part the current rendering state.
+
{{domxref("WebGLRenderingContext.validateProgram()")}}
+
Validates a WebGLProgram.
+
+ +

Uniforms and attributes

+ +
+
{{domxref("WebGLRenderingContext.disableVertexAttribArray()")}}
+
Disables a vertex attribute array at a given position.
+
{{domxref("WebGLRenderingContext.enableVertexAttribArray()")}}
+
Enables a vertex attribute array at a given position.
+
{{domxref("WebGLRenderingContext.getActiveAttrib()")}}
+
Returns information about an active attribute variable.
+
{{domxref("WebGLRenderingContext.getActiveUniform()")}}
+
Returns information about an active uniform variable.
+
{{domxref("WebGLRenderingContext.getAttribLocation()")}}
+
Returns the location of an attribute variable.
+
{{domxref("WebGLRenderingContext.getUniform()")}}
+
Returns the value of a uniform variable at a given location.
+
{{domxref("WebGLRenderingContext.getUniformLocation()")}}
+
Returns the location of a uniform variable.
+
{{domxref("WebGLRenderingContext.getVertexAttrib()")}}
+
Returns information about a vertex attribute at a given position.
+
{{domxref("WebGLRenderingContext.getVertexAttribOffset()")}}
+
Returns the address of a given vertex attribute.
+
{{domxref("WebGLRenderingContext.uniform()", "WebGLRenderingContext.uniform[1234][fi][v]()")}}
+
Specifies a value for a uniform variable.
+
{{domxref("WebGLRenderingContext.uniformMatrix()", "WebGLRenderingContext.uniformMatrix[234]fv()")}}
+
Specifies a matrix value for a uniform variable.
+
{{domxref("WebGLRenderingContext.vertexAttrib()", "WebGLRenderingContext.vertexAttrib[1234]f[v]()")}}
+
Specifies a value for a generic vertex attribute.
+
{{domxref("WebGLRenderingContext.vertexAttribPointer()")}}
+
Specifies the data formats and locations of vertex attributes in a vertex attributes array.
+
+ +

Drawing buffers

+ +
+
{{domxref("WebGLRenderingContext.clear()")}}
+
Clears specified buffers to preset values.
+
{{domxref("WebGLRenderingContext.drawArrays()")}}
+
Renders primitives from array data.
+
{{domxref("WebGLRenderingContext.drawElements()")}}
+
Renders primitives from element array data.
+
{{domxref("WebGLRenderingContext.finish()")}}
+
Blocks execution until all previously called commands are finished.
+
{{domxref("WebGLRenderingContext.flush()")}}
+
Empties different buffer commands, causing all commands to be executed as quickly as possible.
+
+ +

Working with extensions

+ +

These methods manage WebGL extensions:

+ +
+
{{domxref("WebGLRenderingContext.getSupportedExtensions()")}}
+
Returns an {{jsxref("Array")}} of {{domxref("DOMString")}} elements with all the supported WebGL extensions.
+
{{domxref("WebGLRenderingContext.getExtension()")}}
+
Returns an extension object.
+
+ +

Examples

+ +

WebGL context feature detection

+ +

{{page("/en-US/Learn/WebGL/By_example/Detect_WebGL", "summary")}}

+ +

{{page("/en-US/Learn/WebGL/By_example/Detect_WebGL", "detect-webgl-source")}}

+ +

{{EmbedLiveSample("detect-webgl-source", 660,150 ,"" , "Learn/WebGL/By_example/Detect_WebGL")}}

+ +

Effect of canvas size on rendering with WebGL

+ +

{{page("/en-US/Learn/WebGL/By_example/Canvas_size_and_WebGL", "canvas-size-and-webgl-intro")}}

+ +

{{page("/en-US/Learn/WebGL/By_example/Canvas_size_and_WebGL", "canvas-size-and-webgl-source")}}

+ +

{{EmbedLiveSample("canvas-size-and-webgl-source", 660,180 ,"" , "Learn/WebGL/By_example/Canvas_size_and_WebGL")}}

+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WebGL', "#5.14", "WebGLRenderingContext")}}{{Spec2('WebGL')}}Initial definition
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome("9")}}20{{CompatGeckoDesktop("2.0")}}{{CompatIE("11")}}{{CompatOpera("12")}}{{CompatSafari("5.1")}}
Available in workers{{CompatNo}}{{CompatNo}}{{CompatGeckoDesktop(44)}} [1]{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidEdgeFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}25{{CompatVersionUnknown}}{{CompatGeckoMobile("2.0")}}1.0{{CompatUnknown}}128.0
Available in workers{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatGeckoMobile(44)}} [1]{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

[1] This feature is behind a feature preference setting. In about:config, set gfx.offscreencanvas.enabled to true.

+ +

See also

+ + diff --git a/files/de/web/api/websocket/binarytype/index.html b/files/de/web/api/websocket/binarytype/index.html new file mode 100644 index 0000000000..da69c1ec8c --- /dev/null +++ b/files/de/web/api/websocket/binarytype/index.html @@ -0,0 +1,56 @@ +--- +title: WebSocket.binaryType +slug: Web/API/WebSocket/binaryType +tags: + - API + - Eigenschaft + - Referenz + - Web API + - WebSocket +translation_of: Web/API/WebSocket/binaryType +--- +

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

+ +

Die Eigenschaft WebSocket.binaryType gibt den Typ von Binärdaten zurück, der übertragen wird.

+ +

Syntax

+ +
var binaryType = aWebSocket.binaryType;
+ +

Wert

+ +

Ein {{DOMXref("DOMString")}}:

+ +
+
"blob"
+
Wenn {{domxref("Blob")}} Objekte benutzt werden.
+
"arraybuffer"
+
Wenn {{jsxref("ArrayBuffer")}} Objekte benutzt werden. + +
+
+ +

Spezifikationen

+ + + + + + + + + + + + + + + + +
SpezifikationStatusKommentar
{{SpecName('HTML WHATWG', '#dom-websocket-binarytype', 'WebSocket: binaryType')}}{{Spec2('HTML WHATWG')}}Initial definition
+ +

Browser Kompatibilität

+ + + +

{{Compat("api.WebSocket.binaryType")}}

diff --git a/files/de/web/api/websocket/close/index.html b/files/de/web/api/websocket/close/index.html new file mode 100644 index 0000000000..9aec5890d0 --- /dev/null +++ b/files/de/web/api/websocket/close/index.html @@ -0,0 +1,64 @@ +--- +title: WebSocket.close() +slug: Web/API/WebSocket/close +tags: + - API + - Funktion + - Referenz + - Web API + - WebSocket +translation_of: Web/API/WebSocket/close +--- +

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

+ +

Die Funktion WebSocket.close() beendet eine {{domxref("WebSocket")}} Verbindung oder den Versuch eines Verbindungsaufbaus. Wenn diese schon geschlossen ist, passiert nichts weiter.

+ +

Syntax

+ +
WebSocket.close();
+ +

Parameter

+ +
+
code {{optional_inline}}
+
Ein numerisch Wert, der den Status angibt, warum die Verbindung geschlossen wird. Wird kein Wert spezifiziert, . Zur Referenz kann diese Liste mit Codes des {{domxref("CloseEvent")}}s für gültige Werte genommen werden.
+
reason {{optional_inline}}
+
Ein lesbarer Text, welcher erklärt, warum die Verbindung geschlossen wird. Dieser muss UTF-8 kodiert und darf nicht länger als 123 Bytes sein.
+
+ +

Fehler

+ +
+
INVALID_ACCESS_ERR
+
Ein ungültiger code wurde angegeben.
+
SYNTAX_ERR
+
Der reason Text ist zu lang oder enthält ungültige Zeichen.
+
+ +
+

Note: In Gecko unterstützte diese Funktion bis zu Version 8.0 {{geckoRelease("8.0")}} keine Parameter.

+
+ +

Spezifikationen

+ + + + + + + + + + + + + + +
SpezifikationStatusKommentar
HTML Living Standard
+ The definition of 'WebSocket.close()' in that specification.
Living StandardInitial definition
+ +

Browser Kompatibilität

+ + + +

{{Compat("api.WebSocket.close")}}

diff --git a/files/de/web/api/websocket/extensions/index.html b/files/de/web/api/websocket/extensions/index.html new file mode 100644 index 0000000000..bbc5d722c4 --- /dev/null +++ b/files/de/web/api/websocket/extensions/index.html @@ -0,0 +1,49 @@ +--- +title: WebSocket.extensions +slug: Web/API/WebSocket/extensions +tags: + - API + - Eigenschaft + - Referenz + - Web API + - WebSocket +translation_of: Web/API/WebSocket/extensions +--- +

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

+ +

Die Eigenschaft WebSocket.extensions gibt die Erweiterungen des Servers zurück. Sie ist nur lesbar.

+ +

Syntax

+ +
var extensions = aWebSocket.extensions;
+ +

Wert

+ +

Ein {{domxref("DOMString")}}.

+ +

Momentan ist dies entweder ein leerer String oder eine Liste an Erweiterungen, welche zwischen dem Server und dem Client ausgehandelt wurden.

+ +

Spezifikationen

+ + + + + + + + + + + + + + + + +
SpezifikationStatusKommentar
{{SpecName('HTML WHATWG', '#dom-websocket-extensions', 'WebSocket: extensions')}}{{Spec2('HTML WHATWG')}}Initial definition
+ +

Browser Kompatibilität

+ + + +

{{Compat("api.WebSocket.extensions")}}

diff --git a/files/de/web/api/websocket/index.html b/files/de/web/api/websocket/index.html new file mode 100644 index 0000000000..641c788179 --- /dev/null +++ b/files/de/web/api/websocket/index.html @@ -0,0 +1,314 @@ +--- +title: WebSocket +slug: Web/API/WebSocket +tags: + - API + - WebSocket + - WebSockets +translation_of: Web/API/WebSocket +--- +

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

+ +

Das WebSocket-Objekt bietet die API für das Erstellen und Verwalten einer WebSocket-Verbindung zu einem Server, ebenso dient es auch dem Senden und dem Empfangen von Daten auf der Verbindung.

+ +

Der WebSocket-Konstruktor akzeptiert einen benötigten und einen optionalen Parameter:

+ +
WebSocket WebSocket(
+  in DOMString url,
+  in optional DOMString protocols
+);
+
+WebSocket WebSocket(
+  in DOMString url,
+  in optional DOMString[] protocols
+);
+
+ +
+
url
+
Die URL mit der sich das WebSocket verbinden soll; dies sollte die URL sein, auf welcher der WebSocket Server antworten wird.
+
protocols {{ optional_inline() }}
+
Entweder ein einzelnes Protokol als String oder ein Array aus Protokol-Strings. Diese Strings werden genutzt um Sub-Protokolle zu indizieren, sodass ein einzelner Server mehrere WebSocket Sub-Protokolle implementieren kann (Beispielsweiße kann ein Server abhängig vom protocol verschiedene Interaktionen mit dem Client handeln). Falls du kein Protokoll angibst, wird ein leerer String verwendet.
+
+ +

Der Konstruktur kann folgende Exceptions werfen:

+ +
+
SECURITY_ERR
+
Der Port auf dem man die Verbindung aufbauen will, ist blockiert worden.
+
+ +
+
+ +

Methoden Übersicht

+ + + + + + + + + + +
void close(in optional unsigned long code, in optional DOMString reason);
void send(in DOMString data);
+ +

Attribute

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
AttributTypBeschreibung
binaryType{{ DOMXref("DOMString") }}Ein String indiziert den Typ der Binärdaten, die von der Verbindung übertragen werden. Dies sollte entweder "blob" sein, falls DOM-Objekte {{ domxref("Blob") }} genutzt werden oder "arraybuffer" falls ArrayBuffer-Objekte genutzt werden.
bufferedAmountunsigned longDie Anzahl der Bytes der Daten, welche bereits durch Aufrufe von {{ manch("send") }} gebuffert wurden, allerdings noch nicht über das Netzwerk versand wurden. Dieses Feld setzt sich nicht auf Null zurück, wenn die Verbindung beendet wurde; falls du weiterhin {{ manch("send") }} aufrufst, wird dieses Feld weiterhin ansteigen. Read only.
extensions{{ DOMXref("DOMString") }}Die Erweiterungen, die von dem Server gewählt wurden. Aktuell ist dies nur ein leerer String oder eine Liste von Erweiterungen, die von der Verbindung verhandelt wurden.
onclose{{ domxref("EventListener") }}Ein Event-Listener welcher aufgerufen wird, wenn der readyState der WebSocket-Verbindung auf CLOSED wechselt. Den Listener erreicht ein CloseEvent welches "close" heißt.
onerror{{ domxref("EventListener") }}Ein Event-Listener welcher bei Fehlern aufgerufen wird. Dies ist ein einfaches Event welches "error" genannt wird.
onmessage{{ domxref("EventListener") }}Ein Event-Listener welcher aufgerufen wird, wenn eine Nachricht vom Server empfangen wird. Den Listener erreicht ein MessageEvent welches "message" heißt.
onopen{{ domxref("EventListener") }}Ein Event-Listener welcher aufgerufen wird, wenn der readyState der WebSocket-Verbindung auf OPEN wechselt; dies indiziert, dass die Verbindung bereit ist, dass man Daten versenden und empfangen kann. Dieses Event ist eine einfaches Event, es heißt "open".
protocol{{ DOMXref("DOMString") }}Ein String welcher dne Namen des Sub-Protokolls nennt, welches vom Server ausgewählt wurde; dieses Protokoll wird eines sein, welches in den Strings des protocols-Parameter beim Erstellen des WebSocket-Objekt angegeben wurde.
readyStateunsigned shortDer aktuelle Status der Verbindung; dies ist einer der {{ anch("Ready state Konstanten") }}. Read only.
url{{ DOMXref("DOMString") }}Die URL welche beim Konstruktor angegeben wurde. Dies ist immer die absolute URL. Read only.
+ +

Konstanten

+ +

Ready state Konstanten

+ +

Diese Konstanten werden vom readyState Attribut genutzt, um den Status der WebSocket-Verbindung zu beschreiben.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
KonstanteInhaltBeschreibung
CONNECTING0Die Verbindung ist noch nicht hergestellt.
OPEN1Die Verbindung ist hergestellt und bereit darüber zu kommunizieren.
CLOSING2Die Verbindung ist im Prozess des Schließens.
CLOSED3Die Verbindung ist geschlossen oder konnte nicht hergestellt werden.
+ +

Methoden

+ +

close()

+ +

Schließt die WebSocket-Verbindung oder den Verbindungsversuch, falls dieser gerade existiert. Falls die Verbindung bereits CLOSED ist, macht diese Methode überhaupt nichts.

+ +
void close(
+  in optional unsigned short code,
+  in optional DOMString reason
+);
+
+ +
Parameter
+ +
+
code {{ optional_inline() }}
+
Eine Nummer welche den Status-Code setzt, warum die Verbindung geschlossen wird. Falls dieser Parameter nicht gesetzt wird, wird er auf 1005 (welcher bei einer normalen Verbindung "Keinen Status erhalten" bedeutet) gesetzt.
+
reason {{ optional_inline() }}
+
Ein vom Menschen lesbarer String, welcher erklärt, warum die Verbindung geschlossen wurde. Dieser Text darf nicht länger als 123 Bytes UTF-8-Text sein. Dabei heißt dies nicht unbedingt, dass es auch 123 Zeichen sind.
+
+ +
Exceptions thrown
+ +
+
INVALID_ACCESS_ERR
+
Ein ungültiger code wurde gesetzt.
+
SYNTAX_ERR
+
Der reason-String ist zu lang oder enthält ungültige Zeichen.
+
+ +
Notizen
+ +

In Gecko vor Version Gecko 8.0 unterstützte diese Methode überhaupt keine Parameter. {{ geckoRelease("8.0") }}.

+ +

send()

+ +

Überträgt Daten zu dem Server über die WebSocket-Verbindung.

+ +
void send(
+  in DOMString data
+);
+
+void send(
+  in ArrayBuffer data
+);
+
+void send(
+  in Blob data
+);
+
+ +
Parameter
+ +
+
data
+
Ein String der zum Server geschickt wird.
+
+ +
Exceptions thrown
+ +
+
INVALID_STATE_ERR
+
Die Verbindung hat aktuell nicht den Status OPEN.
+
SYNTAX_ERR
+
data enthält ungültige Zeichen.
+
+ +
Erläuterung
+ +
+

Notiz: Geckos Implementierung von der send() Methode unterscheidet sich ein wenig von der Spezifikation in {{Gecko("6.0")}}; Gecko gibt einen boolean zurück, welcher darüber auskunft gibt, ob die Verbindung immer noch hergestellt ist oder nicht (und, durch Erweiterung, dass die Daten erfolgreich gesammelt oder übertragen wurden); dies wurde in {{Gecko("8.0")}} korrigiert.

+ +

In {{Gecko("11.0")}} ist die Unterstützung für  ArrayBuffer implementiert aber nicht die für {{ domxref("Blob") }} Datentypen.

+
+ +

Weiterführendes

+ + + +

Browser Kompatibilität

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{ CompatVersionUnknown() }}{{ CompatGeckoDesktop("2.0") }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatUnknown() }}
Sub-protocol support{{ CompatUnknown() }}{{ CompatGeckoDesktop("6.0") }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{ CompatUnknown() }}{{ CompatGeckoMobile("7.0") }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
Sub-protocol support{{ CompatUnknown() }}{{ CompatGeckoMobile("7.0") }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +

Gecko Notizen

+ +

In Gecko 6.0 ist der Konstruktur mit einem Prefix ausgestattet; du must MozWebSocket() benutzen:

+ +
var mySocket = new MozWebSocket("http://www.example.com/socketserver");
+
+ +

Das extensions-Attribut wurde bis Gecko 8.0 nicht unterstützt.

+ +
Notiz: Vor {{Gecko("11.0")}} ausgehende Nachrichten welche mit der {{ manch("send") }} Methode versendet wurden, waren auf 16 MB begrenzt. Jetzt können sie bis zu 2 GB wachsen.
+ +

{{ languages ( {"zh-tw": "zh_tw/WebSockets/WebSockets_reference/WebSocket"} ) }}

diff --git a/files/de/web/api/websocket/onclose/index.html b/files/de/web/api/websocket/onclose/index.html new file mode 100644 index 0000000000..9e112fb499 --- /dev/null +++ b/files/de/web/api/websocket/onclose/index.html @@ -0,0 +1,45 @@ +--- +title: WebSocket.onclose +slug: Web/API/WebSocket/onclose +tags: + - API + - Eigenschaft + - Referenz + - Web API + - WebSocket +translation_of: Web/API/WebSocket/onclose +--- +

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

+ +

Die Eigenschaft WebSocket.onclose ist ein {{domxref("EventHandler")}}, der aufgerufen wird, wenn die Eigenschaft {{domxref("WebSocket.readyState","WebSocket.readyState")}} zu {{domxref("WebSocket.readyState","CLOSED")}} geändert bzw. die Verbindung geschlossen wird.

+ +

Als Parameter übergeben wird ein {{domxref("CloseEvent")}}.

+ +

Syntax

+ +
aWebSocket.onclose = function(event) {
+  console.log("WebSocket is closed now.");
+};
+ +

Wert

+ +

Ein {{domxref("EventListener")}}.

+ +

Spezifikationen

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#handler-websocket-onclose', 'WebSocket: onclose')}}{{Spec2('HTML WHATWG')}}Initial definition
diff --git a/files/de/web/api/websocket/protocol/index.html b/files/de/web/api/websocket/protocol/index.html new file mode 100644 index 0000000000..ca76edd3a2 --- /dev/null +++ b/files/de/web/api/websocket/protocol/index.html @@ -0,0 +1,51 @@ +--- +title: WebSocket.protocol +slug: Web/API/WebSocket/protocol +tags: + - API + - Eigenschaft + - Referenz + - Web API + - WebSocket +translation_of: Web/API/WebSocket/protocol +--- +

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

+ +

Die Eigenschaft WebSocket.protocol gibt den Namen des Unterprotokolls zurück, welches der Server ausgewählt hat. Sie ist nur lesbar.

+ +

Syntax

+ +
var protocol = aWebSocket.protocol;
+ +

Wert

+ +

A DOMString.

+ +

Entweder ist der String leer, oder enthält den Namen eines der Protokolle, welche im {{domxref("WebSocket")}} Konstruktor mit dem Parameter protocols übergeben wurden.

+ +

Siehe hier.

+ +

Spezifikationen

+ + + + + + + + + + + + + + + + +
SpezifikationStatusKommentar
{{SpecName('HTML WHATWG', '#dom-websocket-protocol', 'WebSocket: protocol')}}{{Spec2('HTML WHATWG')}}Initial definition
+ +

Browser Kompatibilität

+ + + +

{{Compat("api.WebSocket.protocol")}}

diff --git a/files/de/web/api/websocket/readystate/index.html b/files/de/web/api/websocket/readystate/index.html new file mode 100644 index 0000000000..9abc994d65 --- /dev/null +++ b/files/de/web/api/websocket/readystate/index.html @@ -0,0 +1,77 @@ +--- +title: WebSocket.readyState +slug: Web/API/WebSocket/readyState +tags: + - API + - Eigenschaft + - Referenz + - Web API + - WebSocket +translation_of: Web/API/WebSocket/readyState +--- +

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

+ +

Die Eigenschaft WebSocket.readyState gibt den momentanen Status einer {{domxref("WebSocket")}} Verbindung zurück. Sie ist nur lesbar.

+ +

Syntax

+ +
var readyState = aWebSocket.readyState;
+ +

Werte

+ +

Einer der folgenden Werte kann vorhanden sein:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
WertStatusBeschreibung
0CONNECTINGDer Socket wurde erstellt, jedoch besteht noch keine Verbindung.
1OPENEine Verbindung wurde hergestellt und kann zur Kommunikation genutzt werden.
2CLOSINGDie Verbindung wird beendet.
3CLOSEDDie Verbindung wurde geschlossen oder konnte nicht geöffnet werden.
+ +

Spezifikationen

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#dom-websocket-readystate', 'WebSocket: readyState')}}{{Spec2('HTML WHATWG')}}Initial definition
+ +

Browser Kompatibilität

+ + + +

{{Compat("api.WebSocket.readyState")}}

diff --git a/files/de/web/api/websocket/url/index.html b/files/de/web/api/websocket/url/index.html new file mode 100644 index 0000000000..56e0852dea --- /dev/null +++ b/files/de/web/api/websocket/url/index.html @@ -0,0 +1,47 @@ +--- +title: WebSocket.url +slug: Web/API/WebSocket/url +tags: + - API + - Eigenschaft + - Referenz + - Web API + - WebSocket +translation_of: Web/API/WebSocket/url +--- +

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

+ +

Die Eigenschaft WebSocket.url gibt die absolute URL eines {{domxref("WebSocket")}} zurück, wie sie im Konstruktor angegeben wurde. Sie ist nur lesbar.

+ +

Syntax

+ +
var url = aWebSocket.url;
+ +

Wert

+ +

Ein DOMString.

+ +

Spezifikationen

+ + + + + + + + + + + + + + + + +
SpezifikationStatusKommentar
{{SpecName('HTML WHATWG', '#dom-websocket-url', 'WebSocket: url')}}{{Spec2('HTML WHATWG')}}Initial definition
+ +

Browser Kompatibilität

+ + + +

{{Compat("api.WebSocket.url")}}

diff --git a/files/de/web/api/webxr_device_api/index.html b/files/de/web/api/webxr_device_api/index.html new file mode 100644 index 0000000000..69e10d7d3b --- /dev/null +++ b/files/de/web/api/webxr_device_api/index.html @@ -0,0 +1,298 @@ +--- +title: WebXR-Geräte-API +slug: Web/API/WebXR_Device_API +translation_of: Web/API/WebXR_Device_API +--- +

{{APIRef("WebXR Device API")}}{{Draft}}

+ +

WebXR ist eine Gruppe von Standards, die zusammen verwendet werden, um das Rendern von 3D-Szenen auf Hardware zu unterstützen, die für die Darstellung virtueller Welten(Virtuelle Realitätoder VR )entwickelt wurde, oder um der realen Welt grafische Bilder hinzuzufügen (Augmented Realityoder AR). Die WebXR-Geräte-API implementiert den Kern des WebXR-Feature-Sets, verwaltet die Auswahl von Ausgabegeräten, rendert die 3D-Szene mit der entsprechenden Bildrate auf das ausgewählte Gerät und verwaltet Bewegungsvektoren, die mit Eingabecontrollern erstellt wurden.

+ +

WebXR-kompatible Geräte umfassen vollständig immersive 3D-Headsets mit Bewegungs- und Orientierungsverfolgung, Brillen, die Grafiken über der realen Szene überlagern, die durch die Rahmen gehen, und Handheld-Handys, die die Realität erweitern, indem sie die Welt mit einer Kamera erfassen und diese Szene mit computergenerierten Bildern ergänzen.

+ +

Um dies zu erreichen, bietet die WebXR-Geräte-API die folgenden Schlüsselfunktionen:

+ + + +

Auf der grundlegendsten Ebene wird eine Szene in 3D dargestellt, indem die Perspektive berechnet wird, die auf die Szene angewendet werden soll, um sie aus der Sicht jedes benutzerischen Augen zu rendern, wobei der typische Abstand zwischen den Augen berücksichtigt wird, und dann die Szene zweimal, einmal für jedes Auge, gerendert wird. Die resultierenden Bilder (oder Bilder, wenn die Szene zweimal auf einem einzigen Frame gerendert wird, die Hälfte pro Auge) werden dann dem Benutzer angezeigt.

+ +

Da WebGL zum Rendern der 3D-Welt in die WebXR-Sitzung verwendet wird, sollten Sie zunächst mit der allgemeinen Verwendung von WebGL und mit den Grundlagen der 3D-Grafik im Allgemeinen vertraut sein. Sie verwenden höchstwahrscheinlich nicht direkt die WebGL-API, sondern eines der Frameworks oder Bibliotheken, die auf WebGL erstellt werden, um die Verwendung zu erleichtern. Zu den beliebtesten von ihnen ist three.js.

+ +

Ein besonderer Vorteil der Verwendung einer Bibliothek anstelle der direkten Verwendung der WebGL-API besteht darin, dass Bibliotheken dazu neigen, virtuelle Kamerafunktionen zu implementieren. OpenGL (und damit WebGL durch Erweiterung) bietet nicht direkt eine Kameraansicht, mit einer Bibliothek, die eine in Ihrem Namen simuliert kann Ihre Arbeit viel, viel einfacher machen, vor allem beim Erstellen von Code, die freie Bewegung durch Ihre virtuelle Welt ermöglicht.

+ +

Wichtige Gesundheits- und Sicherheitshinweise

+ +

Da der gesamte Akt der Schaffung einer virtuellen 3D-Welt im Wesentlichen ein Trick ist, der unser Verständnis davon nutzt, wie Augen Licht sammeln und wie das Gehirn die gesammelten Daten interpretiert, ist es wichtig zu bedenken, dass Software-Designer und Entwickler als solche die Verantwortung haben, noch vorsichtiger als üblich zu sein, um sicherzustellen, dass die Ergebnisse korrekt sind.

+ +

Defekte, Fehlstellungen oder Verzerrungen können die Augen und das Gehirn verwirren, was zu allem von schmerzenden Augen oder Kopfschmerzen bis hin zu schwindelerregendem Schwindel, Schwindel oder potenziell schwerer Übelkeit führt. Es ist auch wichtig, wachsam zu sein für alles, was Sie anzeigen können, die das Potenzial haben können, Anfälle auszulösen, angesichts der allumfassenden Natur der VR-Brille; Der Benutzer ist möglicherweise nicht in der Lage, schnell von den Bildern wegzuschauen, die Sie präsentieren, wenn es Zuflucht verursacht.

+ +

Wenn Sie Inhalte haben, die für Benutzer von Gefahr sein können, sollten Sie eine Warnmeldung bereitstellen. Besser sicher sein als entschuldigung!

+ +

WebXR Device API-Konzepte und -Nutzung

+ +

WebXR: AR and VR

+ +
+
Example WebXR hardware setup
+Sketch of a person in a chair with wearing goggles labelled "Head mounted display (HMD)" facing a monitor with a webcam labeled "Position sensor"
+ +

While the older WebVR API was designed solely to support Virtual Reality (VR), WebXR provides support for both VR and Augmented Reality (AR) on the web. Support for AR functionality is added by the WebXR Augmented Reality Module.

+ +

A typical XR device can have either 3 or 6 degrees of freedom and might or might not have an external positional sensor.

+ +

The equipment may also include an accelerometer, barometer, or other sensors which are used to sense when the user moves through space, rotates their head, or the like.

+ +

WebXR application lifecycle

+ +

Most applications using WebXR will follow a similar overall design pattern:

+ +
    +
  1. Check to see if the user's device and browser are both capable of presenting the XR experience you want to provide. +
      +
    1. Make sure the WebXR API is available; if {{domxref("navigator.xr")}} is undefined, you can assume the user's browser and/or device doesn't support WebXR. If it's not supported, disable any user interface used to activate XR features and abort any attempts to enter XR mode.
    2. +
    3. Call {{DOMxRef("XR.isSessionSupported","navigator.xr.isSessionSupported()")}}, specifying the WebXR experience mode you want to provide: , , or , in order to determine whether or not the type of session you wish to provide is available.inlineimmersive-vrimmersive-ar
    4. +
    5. If the session type you want to use is available, provide the appropriate interface to the user to allow them to activate it.
    6. +
    +
  2. +
  3. When the user requests the activation of WebXR functionality by engaging with the user interface enabled above, request an {{DOMxRef("XRSession")}} using the desired mode. This is done by calling {{DOMxRef("XR.requestSession","navigator.xr.requestSession()")}}, again specifying the string indicating the mode you want to enable: , , or .inlineimmersive-vrimmersive-ar
  4. +
  5. If the promise returned by  resolves, use the new {{domxref("XRSession")}} to run the frame loop for the entire duration of the WebXR experience.requestSession() +
      +
    1. Call the {{domxref("XRSession")}} method {{DOMxRef("XRSession.requestAnimationFrame", "requestAnimationFrame()")}} to schedule the first frame render for the XR device.
    2. +
    3. Each  callback should use the information provided about the objects located in the 3D world to render the frame using WebGL.requestAnimationFrame()
    4. +
    5. Keep calling {{DOMxRef("XRSession.requestAnimationFrame", "requestAnimationFrame()")}} from within the callback to schedule each successive frame to be rendered.
    6. +
    +
  6. +
  7. When the time comes, end the XR session; otherwise, continue the loop until the user chooses to exit XR mode. +
      +
    1. To end the XR session yourself, call {{DOMxRef("XRSession.end", "XRSession.end()")}}.
    2. +
    3. Include a handler for the {{domxref("XRSession")}} event {{domxref("XRSession.end_event", "end")}} event to be informed when the session is ending, regardless of whether your code, the user, or the browser initiated the termination of the session.
    4. +
    +
  8. +
+ +

Permissions and security

+ +

The WebXR Device API is subject to a number of permission and security controls. While not onerous, they are worth being aware of. These mostly revolve around the fully-immersive  session mode, but there are things to be aware of when setting up an AR session, as well.immersive-vr

+ +

Immersive presentation of VR

+ +

First, any requests to activate the  mode are rejected if the domain issuing the request does not have permission to enable an immersive session. This permission comes from the  feature policy.immersive-vrxr-spatial-tracking

+ +

Once that check is passed, the request to enter mode is allowed if all of the following are true:immersive-vr

+ + + +

If all of that is true, the promise returned by  is resolved, and the new {{domxref("XRSession")}} object is passed into the fulfillment handler. Otherwise, an appropriate exception is thrown, such as  if the document doesn't have permission to enter immersive mode.requestSession()SecurityError

+ +

Inline presentation

+ +

When you request an {{domxref("XRSession")}} with the mode set to , and any features are required or requested, the browser will only allow the session to be created if the call to {{domxref("XR.requestSession", "requestSession()")}} was made by code which is executing expressly due to user intent.inline

+ +

Specifically:

+ + + +
+

Note: Additional requirements may be put into effect due to the specific features requested by the options object when calling .requestSession()

+
+ +

User intent

+ +

User intent is the concept of whether or not an action being performed by code is being performed because of something the user intends to do or not. There are two kinds of user intent: implicit and explicit.

+ +

Explicit user intent (explicit user consent) is granted when the user has specifically and expressly been asked for permission to perform an action.

+ +

Implicit user intent (implicit user consent) is assumed if either of the following scenarios is the case:

+ + + +

WebXR availability

+ +

As a new and still in development API, WebXR support is limited to specific devices and browsers; and even on those, it may not be enabled by default. There may be options available to allow you to experiment with WebXR even if you don't have a compatible system, however.

+ +

WebXR polyfill

+ +

The team designing the WebXR specification has published a WebXR polyfill which you can use to simulate WebXR on browsers which don't have support for the WebXR APIs. If the browser supports the older WebVR API, that is used. Otherwise, the polyfill falls back to an implementation which uses Google's Cardboard VR API.

+ +

The polyfill is maintained alongside the specification, and is kept up to date with the specification. Additionally, it is updated to maintain compatibility with browsers as their support for WebXR and other technologies related to it and to the implementation of the polyfill change over time.

+ +

Be sure to read the readme carefully; the polyfill comes in several versions depending on what degree of compatibility with newer JavaScript features your target browsers include.

+ +

WebXR API Emulator extension

+ +

The Mozilla WebXR team has created a WebXR API Emulator browser extension, compatible with both Firefox and Chrome, which emulates the WebXR API, simulating a variety of compatible devices such as the HTC Vive, the Oculus Go and Oculus Quest, Samsung Gear, and Google Cardboard. With the extension in place, you can open up a developer tools panel that lets you control the position and orientation of the headset and any hand controllers, as well as button presses on the controllers.

+ +
Emulator usage
+ +

While somewhat awkward compared to using an actual headset, this makes it possible to experiment with and developer WebXR code on a desktop computer, where WebXR isn't normally available. It also lets you perform some basic testing before taking your code to a real device. Be aware, however, that the emulator does not yet completely emulate all of the WebXR API, so you may run into problems you're not expecting. Again, carefully read the readme file and make sure you're aware of the limitations before you begin.

+ +
+

Important: You should always test your code on actual AR and/or VR hardware before releasing or shipping a product! Emulated, simulated, or polyfilled environments are not an adequate substitute for actual testing on physical devices.

+
+ +
Getting the extension
+ +

Download the WebXR API Emulator for your supported browser below:

+ + + +

The source code for the extension is also available on GitHub.

+ +
Emulator issues and notes
+ +

While this isn't the place for a full article about the extension, there are some specific things worth mentioning.

+ +

Version 0.4.0 of the extension was announced on March 26, 2020. It introduced support for augmented reality (AR) through the WebXR AR Module, which has is approaching a stable state. Documentation for AR is forthcoming shortly here on MDN.

+ +

Other improvements include updating the emulator to rename the  interface to {{domxref("XRSystem")}}, introduce support for squeeze (grip) input sources, and add support for the {{domxref("XRInputSource")}} property {{domxref("XRInputSource.profiles", "profiles")}}.XR

+ +

Accessing the WebXR API

+ +

To gain access to the WebXR API within the context of a given window, use the {{domxref("navigator.xr")}} property.

+ +
+
{{domxref("navigator.xr")}} {{ReadOnlyInline}}
+
This property, added to the {{domxref("Navigator")}} interface, returns the {{domxref("XR")}} object through which the WebXR API is exposed. If this property is missing or , WebXR is not available.null
+
+ +

WebXR interfaces

+ +
+
{{DOMxRef("XR")}}
+
The {{domxref("Navigator.xr", "navigator.xr")}} property returns the window's instance of {{domxref("XR")}}, which is the mechanism by which your code accesses the WebXR API. Using the  interface, you can create {{domxref("XRSession")}}s to represent actual AR and/or VR sessions.XR
+
{{DOMxRef("XRFrame")}}
+
While presenting an XR session, the state of all tracked objects which make up the session are represented by an . To get an , call the session's {{domxref("XRSession.requestAnimationFrame", "requestAnimationFrame()")}} method, providing a callback which will be called with the  once available. Events which communicate tracking states will also use  to contain that information.XRFrameXRFrameXRFrameXRFrame
+
{{DOMxRef("XRRenderState")}}
+
Provides a set of configurable properties which change how the imagery output by an  is composited.XRSession
+
{{DOMxRef("XRSession")}}
+
Provides the interface for interacting with XR hardware. Once an  is obtained from {{domxref("XR.requestSession()")}}, the session can be used to check the position and orientation of the viewer, query the device for environment information, and present the virtual or augmented world to the user.XRSession
+
{{DOMxRef("XRSpace")}}
+
XRSpace is an opaque base class on which all virtual coordinate system interfaces are based. Positions in WebXR are always expressed in relation to a particular  at the time at which a particular {{domxref("XFrame")}} takes place. The space's coordinate system has its origin at the a given physical position.XRSpace
+
{{DOMxRef("XRReferenceSpace")}}
+
A subclass of {{domxref("XRSpace")}} which is used to identify a spatial relationship in relation to the user's physical environment. The  coordinate system is expected to remain unchanged through the lifespan of the {{domxref("XRSession")}}.The world has no boundaries and extends infinitely in every direction.XRReferenceSpace
+
{{DOMxRef("XRBoundedReferenceSpace")}}
+
XRBoundedReferenceSpace extends the {{domxref("XRReferenceSpace")}} coordinate system to further include support for a finite world with set boundaries. Unlike , the origin must be located on the floor (that is, y = 0 at the floor). The x and z components of the origin are typically presumed to be located at or near the center of the room or surface.XRReferenceSpace
+
{{DOMxRef("XRView")}}
+
Represents a single view into the XR scene for a particular frame. Each  corresponds to the video display surface used to present the scene to the user. For example, a given XR device might have two views: one for the left eye and one for the right. Each view has an offset used to shift the position of the view relative to the camera, in order to allow for creating stereographic effects.XRView
+
{{DOMxRef("XRViewport")}}
+
Describes a viewport. A viewport is a rectangular portion of a graphic surface.
+
{{DOMxRef("XRRigidTransform")}}
+
A transform defined using a position and orientation in the virtual space's coordinate system as described by the {{domxref("XRSpace")}}.
+
{{DOMxRef("XRPose")}}
+
Describes a position and orientation in space relative to an {{domxref("XRSpace")}}.
+
{{DOMxRef("XRViewerPose")}}
+
Based on {{domxref("XRPose")}},  specifies the state of a viewer of the WebXR scene as indicated by the XR device. Included is an array of {{domxref("XRView")}} objects, each representing one perspective on the scene. For example, it takes two views to create the stereoscopic view as perceived by human vision—one for the left eye and a second for the right eye. One view is offset to the left slightly from the viewer's position, and the other view is offset to the right by the same distance. The view list can also be used to represent the perspectives of each of the spectators of a scene, in a multi-user environment.XRViewerPose
+
{{DOMxRef("XRInputSource")}}
+
Represents any input device the user can use to perform targeted actions within the same virtual space as the viewer. Input sources may include devices such as hand controllers, optical tracking systems, and other devices which are explicitly associated with the XR device. Other input devices such as keyboards, mice, and gamepads are not presented as  instances.XRInputSource
+
{{DOMxRef("XRWebGLLayer")}}
+
A layer which serves as a WebGL frame buffer into which a scene's view is rendered. Using WebGL to render the scene gains substantial performance benefits due to graphics acceleration.
+
+ +

Event interfaces

+ +

The following interfaces are used to represent the events used by the WebXR API.

+ +
+
{{domxref("XRInputSourceEvent")}}
+
Sent when the state of an {{domxref("XRInputSource")}} changes. This can happen, for example, when the position and/or orientation of the device changes, or when buttons are pressed or released.
+
{{domxref("XRInputSourcesChangeEvent")}}
+
Sent to indicate that the set of available input sources has changed for the {{domxref("XRSession")}}.
+
{{domxref("XRReferenceSpaceEvent")}}
+
Sent when the state of an {{domxref("XRReferenceSpace")}} changes.
+
{{domxref("XRSessionEvent")}}
+
Sent to indicate that the state of an {{domxref("XRSession")}} has changed. For example, if the position and/or orient
+
+ +

Extensions to the WebGL API

+ +

The WebGL API is extended by the WebXR specification to augment the WebGL context to allow it to be used to render views for display by a WebXR device.

+ +
+
{{domxref("WebGLRenderingContextBase.makeXRCompatibile()")}}
+
Configures the WebGL context to be compatible with WebXR. If the context was not initially created with the {{domxref("WebGLContextAttributes.xrCompatible", "xrCompatible")}} property set to , you must call  prior to attempting to use the WebGL context for WebXR rendering. Returns a {{jsxref("promise")}} which resolves once the context has been prepared, or is rejected if the context cannot be configured for use by WebXR.truemakeXRCompatible()
+
+ +

Guides and tutorials

+ +

The following guides and tutorials are a great resource to learn how to comprehend WebXR and the underlying 3D and VR/AR graphics concepts.

+ +
+
Fundamentals of WebXR
+
Before diving into the details of how to create content using WebXR, it may be helpful to read this overview of the technology, which includes introductions to terminology that may be unfamiliar to you, or which may be used in a new way.
+
Matrix math for the web
+
A guide covering how matrices can be used on the web, including both for CSS transforms and for WebGL purposes, as well as to handle the positioning and orientation of objects in WebXR contexts.
+
Setting up and shutting down a WebXR session
+
Before actually presenting a scene using an XR device such as a headset or goggles, you need to create a WebXR session bound to a rendering layer that draws the scene for presentation in each of the XR device's displays so that the 3D effect can be presented to the user. This guide covers how to create and stop WebXR sessions.
+
Permissions and security for WebXR
+
The WebXR Device API has several areas of security to contend with, from establishing feature-policy to ensuring the user intends to use the mixed reality presentation before activating it.
+
Geometry and reference spaces in WebXR
+
In this guide, the required concepts of 3D geometry are briefly reviewed, and the fundamentals of how that geometry is represented in WebXR are detailed. Learn how reference spaces are used to position objects—and the viewer—and the differences among the available types of reference space, as well as their use cases.
+
Spatial tracking in WebXR
+
This guide describes how objects—including the user's body and its parts—are located in space, and how their movement and orientation relative to one another is monitored and managed over time. This article explains the relationship between spaces, poses, viewers, and views.
+
Rendering and the WebXR frame loop
+
Starting with how you schedule frames to be rendered, this guide then continues to cover how to determine the placement of objects in the view and how to then render them into the WebGL buffer used for each of the two eyes' views of the scene.
+
Viewpoints and viewers: Simulating cameras in WebXR
+
WebGL (and therefore WebXR) doesn't really have a concept of a camera, which is the traditional concept used to represent a viewpoint in 3D graphics. In this article, we see how to simulate a camera and how to create the illusion of moving a viewer through a world in which the viewer doesn't really move.
+
Movement, orientation, and motion: A WebXR example
+
In this example and tutorial, we use information learned throughout the WebXR documentation to create a scene containing a rotating cube which the user can move around using both VR headset and keyboard and mouse.
+
Using bounded reference spaces
+
In this article, we examine how to use a  reference space to define the boundaries of where the viewer can safely move about without leaving the area tracked by their XR hardware or colliding with a physical obstacle. On devices which support it,  can be a useful tool in your repertoire.bounded-floorbounded-floor
+
WebXR performance guide
+
Recommendations and tips to help you optimize the performance of your WebXR application.
+
Inputs and input sources
+
A guide to input sources and how to efficiently manage the input devices being used to control the WebXR session, and how to receive and process user inputs from those devices.
+
Using WebXR input profiles
+
A guide to interpreting the {{Glossary("JSON")}} data provided by the WebXR Input Profiles Registry, which can be used to determine what options and controls are available on the user's available input devices.
+
Supporting advanced controllers and gamepads in WebXR applications
+
WebXR uses the {{domxref("Gamepad")}} object to describe the controls available on complex input devices (such as hand controllers with multiple buttons and/or axes) and gamepad-like devices. In this guide, learn how to make use of these devices' controls.
+
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("WebXR")}}{{Spec2("WebXR")}}Initial definition.
+ +

Browser compatibility

+ +

{{Compat("api.Navigator.xr")}}

+ +

See also

+ + diff --git a/files/de/web/api/window/alert/index.html b/files/de/web/api/window/alert/index.html new file mode 100644 index 0000000000..841600419d --- /dev/null +++ b/files/de/web/api/window/alert/index.html @@ -0,0 +1,72 @@ +--- +title: Window.alert +slug: Web/API/Window/alert +tags: + - API + - DOM + - Method + - Reference + - Window +translation_of: Web/API/Window/alert +--- +

{{ APIRef }}

+ +

Die Window.alert() Methode zeigt einen Alert-Dialog mit optional spezifiziertem Inhalt und einem OK-Button an.

+ +

Syntax

+ +
window.alert(nachricht);
+ + + +

Beispiel

+ +
window.alert("Hello world!");
+
+ +

erzeugt:

+ +

Image:AlertHelloWorld.png

+ +

Mehr JS:

+ +
alert()
+ +

Anmerkungen

+ +

Der Alert-Dialog sollte für Nachrichten benutzt werden, die keine Reaktion des Nutzers benötigen, außer seiner/ihrer Bestätigung.

+ +

Dialog-Boxen sind modale Fenster - der Rest der Oberfläche wird erst geladen, sobald die Box geschlossen wird. Deswegen sollten Funktionen, die Dialog-Boxen (oder modale Fenster) erzeugen, nicht zu oft benutzt werden.

+ +

Mozilla Chrome-Nutzer (z. B. Firefox-Erweiterungen) sollten stattdessen Methoden des {{interface("nsIPromptService")}} verwenden.

+ +

Ab Chrome {{CompatChrome(46.0)}} wird diese Methode innerhalb eines {{htmlelement("iframe")}} geblockt, solange sein Sandbox-Attribut nicht den Wert allow-modal enthält.

+ +

{{gecko_minversion_inline("23.0")}} Das Argument ist nun optional, wie von der Spezifikation gefordert.

+ +

Spezifikationen

+ + + + + + + + + + + + + + +
SpezifikationStatusKommentar
{{SpecName('HTML5 Web application', '#dom-alert', 'alert()')}}{{Spec2('HTML5 Web application')}}Anfängliche Definition
+ +

Siehe auch

+ + diff --git a/files/de/web/api/window/applicationcache/index.html b/files/de/web/api/window/applicationcache/index.html new file mode 100644 index 0000000000..c8d47fc6ee --- /dev/null +++ b/files/de/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}}

+ +

Zusammenfassung

+ +

Liefert eine Referenz auf das ApplicationCache Objekt für das aktuelle Fenster.

+ +

Syntax

+ +
cache = window.applicationCache
+
+ +

Parameter

+ + + +

Spezification

+ + + +

Siehe auch

+ + diff --git a/files/de/web/api/window/cancelanimationframe/index.html b/files/de/web/api/window/cancelanimationframe/index.html new file mode 100644 index 0000000000..7d38ab5be4 --- /dev/null +++ b/files/de/web/api/window/cancelanimationframe/index.html @@ -0,0 +1,72 @@ +--- +title: Window.cancelAnimationFrame() +slug: Web/API/Window/cancelAnimationFrame +tags: + - API + - Animation + - DOM + - Experimentell + - Méthode +translation_of: Web/API/Window/cancelAnimationFrame +--- +
{{APIRef}}{{SeeCompatTable}}
+ +

Zusammenfassung

+ +

Stopt eine vorher durch {{domxref("window.requestAnimationFrame()")}} geplante Animation.

+ +

Syntax

+ +
window.cancelAnimationFrame(requestID);
+
+ +

Parameter

+ +
+
requestID
+
Der ID Wert der beim Aufruf von {{domxref("window.requestAnimationFrame()")}} vorher zurückgegeben wurde.
+
+ +

Beispiel

+ +
var requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame ||
+                            window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;
+
+var cancelAnimationFrame = window.cancelAnimationFrame || window.mozCancelAnimationFrame;
+
+var start = window.mozAnimationStartTime;  // Nur unterstützt in FF. Andere Browsers können zB Date.now() benutzen.
+
+var myReq;
+
+function step(timestamp) {
+  var progress = timestamp - start;
+  d.style.left = Math.min(progress/10, 200) + "px";
+  if (progress < 2000) {
+    myReq = requestAnimationFrame(step);
+  }
+}
+myReq = requestAnimationFrame(step);
+
+window.cancelAnimationFrame(myReq);
+
+ +

Browserkompatibilität

+ + + +

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

+ +

Spezifikation

+ + + +

Siehe auch

+ + diff --git a/files/de/web/api/window/close/index.html b/files/de/web/api/window/close/index.html new file mode 100644 index 0000000000..84c1630838 --- /dev/null +++ b/files/de/web/api/window/close/index.html @@ -0,0 +1,78 @@ +--- +title: Window.close() +slug: Web/API/Window/close +tags: + - API + - DOM + - Gecko + - Method + - Reference + - Window +translation_of: Web/API/Window/close +--- +
{{APIRef}}
+ +

Die Window.close() Methode schließt das aktuelle Fenster oder das Fenster von dem sie aufgerufen wurde.

+ +

Diese Methode kann nur von Fenstern aufgerufen werden, die ein Skript mit der {{domxref("Window.open()")}} Methode verwenden. Wenn das Fenster nicht durch ein Skript geöffnet wurde, erscheint ein so oder ähnlich lautender Fehler in der Konsole Skripte können keine Fenster schließen, die nicht von ihnen geöffnet wurden.

+ +

Zu beachten ist auch, dass close() keinen Effekt auf {{domxref("Window")}} Objekte hat, die per HTMLIFrame​Element​.content​Window zurückgegeben werden.

+ +

Syntax

+ +
window.close();
+ +

Beispiele

+ +

Schließt ein Fenster, geöffnet durch window.open()

+ +

Dieses Beispiel zeigt eine Funktion die ein Fenster öffnet eine zweite Funktion die es schließt. Das demonstriert wie Window.close() verwendet wird um ein Fenster zu schließen, das per {{domxref("window.open()")}} geöffnet wurde.

+ +
//Global var to store a reference to the opened window
+var openedWindow;
+
+function openWindow() {
+  openedWindow = window.open('moreinfo.htm');
+}
+
+function closeOpenedWindow() {
+  openedWindow.close();
+}
+
+ +

Das aktuelle Fenster schließen

+ +

Wenn Sie in der Vergangenheit die close() Methode des window Objekts direkt aufgerufen haben, anstatt close() für eine window Instanz aufzurufen, hat der Browser das vorderste Fenster geschlossen, unabhängig davon, ob Ihr Skript dieses Fenster erstellt hat oder nicht. Dies ist nicht länger der Fall; Aus Sicherheitsgründen dürfen Skripte keine Fenster mehr schließen, die sie nicht geöffnet haben. (Firefox 46.0.1: Skripte können keine Fenster schließen, die sie nicht geöffnet hatten)

+ +
function closeCurrentWindow() {
+  window.close();
+}
+
+ +

Spezifikation

+ + + + + + + + + + + + + + + + + + + +
SpezifikationStatusKommentar
{{SpecName('HTML WHATWG', '#dom-window-close', 'window.close()')}}{{Spec2('HTML WHATWG')}}
{{SpecName('HTML5 W3C', "browsers.html#dom-window-close", "Window.close()")}}{{Spec2('HTML5 W3C')}}
+ +

Browserkompatibilität

+ + + +

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

diff --git a/files/de/web/api/window/confirm/index.html b/files/de/web/api/window/confirm/index.html new file mode 100644 index 0000000000..23df4db917 --- /dev/null +++ b/files/de/web/api/window/confirm/index.html @@ -0,0 +1,73 @@ +--- +title: Window.confirm() +slug: Web/API/Window/confirm +tags: + - API + - DOM + - Method + - NeedsBrowserCompatibility + - NeedsCompatTable + - NeedsMobileBrowserCompatibility + - Reference + - Window + - confirm +translation_of: Web/API/Window/confirm +--- +
{{ApiRef("Window")}}
+ +

Die Window.confirm() Funktion zeigt ein modales Dialogfenster mit einem optionalen Text und zwei Buttons an, OK und Abbrechen.

+ +

Syntax

+ +
eingabe = window.confirm(nachricht);
+ + + +

Beispiel

+ +
if (window.confirm("Willst du die Seite wirklich verlassen?")) {
+    window.open("exit.html", "Auf Wiedersehen!");
+}
+
+ +

Erzeugt (englisch):

+ +

firefox confirm
+  

+ +

Anmerkungen

+ +

The following text is shared between this article, DOM:window.prompt and DOM:window.alert Dialogfenster sind modal - sie verhindern, dass der Anwender auf den Rest der Seite zugreifen kann, bis das Dialogfenster geschlossen wurde. Aus diesen Grund sollte man Funktionen, die Dialogfenster anzeigen, nicht zu oft verwenden. Und unabhängig davon gibt es gute Gründe dafür, Dialogfenster zum Bestätigen einer Aktion zu vermeiden.

+ +

Mozilla Chrome-Nutzer (z.B. Firefox-Erweiterungen) sollten stattdessen {{interface("nsIPromptService")}} verwenden.

+ +

Seit Chrome {{CompatChrome(46.0)}} wird diese Funktion innerhalb eines {{htmlelement("iframe")}}s blockiert, es sei denn, dessen sandbox-Attribut hat den Wert allow-modal.

+ +

{{gecko_minversion_inline("23.0")}} Der Parameter ist optional und wird laut Spezifikation nicht benötigit.

+ +

Spezifikation

+ + + + + + + + + + + + + + +
SpezifikationStatusKommentar
{{SpecName('HTML WHATWG', 'timers-and-user-prompts.html#dom-confirm', 'confirm()')}}{{Spec2('HTML WHATWG')}} 
+ +

Siehe auch

+ + diff --git a/files/de/web/api/window/console/index.html b/files/de/web/api/window/console/index.html new file mode 100644 index 0000000000..2fa7d75001 --- /dev/null +++ b/files/de/web/api/window/console/index.html @@ -0,0 +1,56 @@ +--- +title: Window.console +slug: Web/API/Window/console +tags: + - API + - Eigenschaft + - Referenz + - Schreibgeschützt + - Window + - console +translation_of: Web/API/Window/console +--- +

{{ APIRef }}

+ +

Die Window.console Eigenschaft gibt eine Referenz des {{domxref("Console")}} Objects zurück, welches Methoden für das Loggen von Informationen in der Browser Konsole bietet. Diese Methoden sollten nur für das Debugging genutzt werden und nicht für das Darstellen von Informationen an Endnutzer.

+ +

Syntax

+ +
var consoleObj = window.console;
+
+ +

Beispiele

+ +

Zur Konsole loggen

+ +

Das erste Beispiel loggt text zur Konsole.

+ +
console.log("Während dem Laden ist ein Fehler aufgetreten.");
+
+ +

Das nächste Beispiel loggt ein Objekt in der Konsole. Die Felder des Objekts können dabei ausgeklappt werden:

+ +
console.dir(einObjekt);
+ +

Schau dir {{SectionOnPage("/de-DE/docs/Web/API/Console", "Nutzung")}} für weitere Beispiele an.

+ +

Spezifikationen

+ + + + + + + + + + + + + + +
SpezifikationStatusKommentar
{{SpecName('Console API')}}{{Spec2('Console API')}}Anfängliche Definition.
+ +
+

Aktuell gibt es viele Unterschiede in der Implementation zwischen den verschiedenen Browsern. Dennoch wird aktuell daran gearbeitet, die Implementationen zusammen zu bringen und konsistenter zu machen.

+
diff --git a/files/de/web/api/window/dump/index.html b/files/de/web/api/window/dump/index.html new file mode 100644 index 0000000000..4126c3a4db --- /dev/null +++ b/files/de/web/api/window/dump/index.html @@ -0,0 +1,42 @@ +--- +title: Window.dump() +slug: Web/API/Window/dump +tags: + - DOM +translation_of: Web/API/Window/dump +--- +
{{ApiRef}}
+ +

Übersicht

+ +

Schreibt eine Nachricht auf die (systemeigene) Konsole.

+ +

Syntax

+ +
window.dump(message);
+
+dump(message);
+
+ + + +

Bemerkungen

+ +

dump wird normalerweise verwendet um JavaScript zu debuggen. Privilegierter Code kann auch Components.utils.reportError und nsIConsoleService verwenden, um Nachrichten in die Fehler-Konsole zu schreiben.

+ +

In Gecko ist dump standardmäßig deaktiviert – beim Aufruf passiert also nichts und es wird auch kein Fehler erzeugt. Um die dump Ausgabe zu sehen, muss die Einstellung browser.dom.window.dump.enabled auf true gesetzt werden. Diese Einstellung kann in about:config oder in der user.js Datei vorgenommen werden. Anmerkung: Diese Einstellung ist in about:config normalerweise nicht enthalten, sie muss erst erzeugt werden (Rechtsklick in den Fensterbereich -> Neu -> Boolean).

+ +

In Windows benötigt man eine Konsole, um überhaupt etwas zu sehen. Wenn noch keine vorhanden ist, kann durch einen Neustart der Anwendung mit dem Parameter  -console eine Konsole erzeugt werden. Auf anderen Betriebssystemen ist es ausreichend die Anwendung aus einem Terminal aufzurufen.

+ +

Um die Konsolenausgabe in eine Datei umzuleiten, muss Firefox ohne den Parameter -console gestartet und folgende Syntax zum Umleiten von stderr und stdout in eine Datei verwendet werden, zB.:

+ +
firefox > console.txt 2>&1
+
+ +

dump steht auch in JavaScript geschriebenen XPCOM Komponenten zur verfügbar, obwohl window nicht das globale Objekt in Komponenten ist. Allerdings wird diese Verwendung von dump nicht durch die oben genannte Einstellung beeinflusst -- die Ausgabe findet immer statt. Deshalb ist es anzuraten, diese Einstellung selbst zu prüfen oder eine eigene Debug-Einstellung zu erzeugen. Damit sichergestellt ist, dass nicht unnötig viele Debug-Daten in die Konsole des Benutzers geschrieben werden, wenn dieser überhaupt nicht an diesen interessiert ist. Achtung, die Ausgabe von dump von XPCOM Komponenten wird zu stderr geleitet, während ein Aufruf von dump an andere Stelle auf stdout ausgibt.

+ +

Spezifikation

+ +

{{DOM0}}

diff --git a/files/de/web/api/window/history/index.html b/files/de/web/api/window/history/index.html new file mode 100644 index 0000000000..05a369435f --- /dev/null +++ b/files/de/web/api/window/history/index.html @@ -0,0 +1,56 @@ +--- +title: Window.history +slug: Web/API/Window/history +tags: + - API + - HTML DOM + - History API + - Window +translation_of: Web/API/Window/history +--- +

{{ APIRef }}

+ +

Die nur lesend zugreifbare Eigenschaft Window.history gibt eine Referenz auf das {{domxref("History")}} Objekt zurück, welches eine Schnittstelle zur Manipulation der Browser Sitzungs-Historie bereitstellt (Seiten, die im aktuellen Tab oder dem aktuellen Frame besucht wurden).

+ +

Unter Manipulating the browser history finden sie weitere Details und Beispiele. Der Artikel geht besonders auf die Sicherheits-Features der Methoden pushState() und replaceState() ein, die Sie vor Benutzung der Funktionen kennen sollten.

+ +

Syntax

+ +
var historyObj = window.history;
+
+ +

Beispiel

+ +
history.back();     // entspricht dem Klicken des "Zurück"-Kopfes
+history.go(-1);     // entspricht history.back();
+
+ +

Anmerkungen

+ +

Für Seiten auf der obersten Ebene kann in der Sitzungs-Historie eine Liste von Seiten über das History Objekt angesehen werden, zugreifbar über die Drop-Downs im Browser neben den Vor- und Zurück-Schaltflächen.

+ +

Aus Sicherheitsgründen erlaubt das History Objekt keinen Zugriff für nicht-privilegierten Code auf die URLs anderer Seiten in der Sitzungs-Historie, erlaubt aber die Navigation durch die Historie.

+ +

Die Sitzungs-Historie kann nicht gelöscht oder das Vor-und Zurück-Navigieren verhindert werden. Die nächstbeste Lösung ist die location.replace() Methode, die den aktuellen Eintrag in der Sitzungs-Historie durch die übergebene URL ersetzt.

+ +

Spezifikationen

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{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/de/web/api/window/index.html b/files/de/web/api/window/index.html new file mode 100644 index 0000000000..26f27d9af0 --- /dev/null +++ b/files/de/web/api/window/index.html @@ -0,0 +1,384 @@ +--- +title: Window +slug: Web/API/Window +tags: + - DOM + - Gecko +translation_of: Web/API/Window +--- +

{{APIRef}}

+ +

Das window Objekt repräsentiert ein Fenster (Window), das ein DOM Dokument enthält. Das document Attribut zeigt auf das DOM document, das im Fenster geladen ist. Für ein gegebenes Dokument kann man über das {{Domxref("document.defaultView")}} Attribut das Fenster abrufen.

+ +

Dieser Abschnitt bietet eine kurze Referenz für alle Methoden, Attribute und Events, die über das window Objekt zur Verfügung stehen. Das window Objekt implementiert die Window Schnitstelle, die wiederrum von der AbstractView Schnittstelle erbt. Einige zusätzliche globale Funktionen, Namespace Objekte, Schnittstellen und Konstruktoren, die nicht typischerweise mit dem Window in Verbindung gebracht werden, aber durch dieses verfügbar sind, werden in der JavaScript Reference und DOM Reference aufgelistet.

+ +

In einem "getabten" Browser wie Firefox enthält jeder Tab sein eigenes Window-Objekt (und im Falle von Extensions ist das Browser-Fenster selbst ein eigenständiges Fenster – siehe auch "Working with windows in chrome code". Das heisst also, dass das Window-Objekt nicht zwischen Tabs desselben Fensters geteilt wird. Einige Methoden, zum Beispiel {{Domxref("window.resizeTo")}} und {{Domxref("window.resizeBy")}} beziehen sich auf das "ganze" Fenster, und nicht auf den Tab, dem das Window-Objekt gehört. Grundsätzlich lässt sich sagen, das alles, was man nicht sinnvollerweise einem Tab zuordnen kann, sich stattdessen auf das Window bezieht.

+ +

Properties

+ +

This interface inherits properties from the {{domxref("EventTarget")}} interface and implements properties from {{domxref("WindowTimers")}}, {{domxref("WindowBase64")}}, and {{domxref("WindowEventHandlers")}}.

+ +

Note that properties which are objects (e.g.,. for overriding the prototype of built-in elements) are listed in a separate section below.

+ +
+
{{domxref("Window.applicationCache")}} {{readOnlyInline}} {{gecko_minversion_inline("1.9")}}
+
An {{domxref("OfflineResourceList")}} object providing access to the offline resources for the window.
+
{{domxref("Window.closed")}} {{Non-standard_inline}}{{readOnlyInline}}
+
This property indicates whether the current window is closed or not.
+
Window.Components {{Non-standard_inline}}
+
The entry point to many XPCOM features. Some properties, e.g. classes, are only available to sufficiently privileged code. Web code should not use this property.
+
{{domxref("console","Window.console")}} {{Non-standard_inline}} {{ReadOnlyInline}}
+
Returns a reference to the console object providing access to the browser's debugging console.
+
{{domxref("Window.content")}} and Window._content {{Non-standard_inline}} {{obsolete_inline}}{{ReadOnlyInline}}
+
Returns a reference to the content element in the current window. The obsolete variant with underscore is no longer available from Web content.
+
{{domxref("Window.controllers")}}{{non-standard_inline}}{{ReadOnlyInline}}
+
Returns the XUL controller objects for the current chrome window.
+
{{domxref("Window.crypto")}} {{readOnlyInline}}
+
Returns the browser crypto object.
+
{{domxref("Window.defaultStatus")}} {{Obsolete_inline("gecko23")}}
+
Gets/sets the status bar text for the given window.
+
{{domxref("Window.devicePixelRatio")}} {{non-standard_inline}}{{ReadOnlyInline}}
+
Returns the ratio between physical pixels and device independent pixels in the current display.
+
{{domxref("Window.dialogArguments")}} {{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}}
+
Returns a reference to the document that the window contains.
+
{{domxref("Window.frameElement")}} {{readOnlyInline}}
+
Returns the element in which the window is embedded, or null if the window is not embedded.
+
{{domxref("Window.frames")}} {{readOnlyInline}}
+
Returns an array of the subframes in the current window.
+
{{domxref("Window.fullScreen")}} {{gecko_minversion_inline("1.9")}}
+
This property indicates whether the window is displayed in full screen or not.
+
{{domxref("window.globalStorage")}} {{gecko_minversion_inline("1.8.1")}} {{Non-standard_inline}} {{Obsolete_inline("gecko13")}}
+
Unsupported since Gecko 13 (Firefox 13). Use {{domxref("Window.localStorage")}} instead.
+ Was: Multiple storage objects that are used for storing data across multiple pages.
+
{{domxref("Window.history")}} {{ReadOnlyInline}}
+
Returns a reference to the history object.
+
{{domxref("Window.innerHeight")}}
+
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("Window.localStorage")}} {{readOnlyInline}}{{gecko_minversion_inline("1.9.1")}}
+
Returns a reference to the local storage object used to store data that may only be accessed by the origin that created it.
+
{{domxref("Window.menubar")}} {{ReadOnlyInline}}
+
Returns the menubar object, whose visibility can be toggled in the window.
+
{{domxref("Window.messageManager")}} {{gecko_minversion_inline("2.0")}}
+
Returns the message manager object for this window.
+
{{domxref("Window.mozAnimationStartTime")}} {{ReadOnlyInline}}{{gecko_minversion_inline("2.0")}}
+
The time in milliseconds since epoch at which the current animation cycle began.
+
{{domxref("Window.mozInnerScreenX")}} {{ReadOnlyInline}}{{non-standard_inline}}{{gecko_minversion_inline("1.9.2")}}
+
Returns the horizontal (X) coordinate of the top-left corner of the window's viewport, in screen coordinates. This value is reported in CSS pixels. See mozScreenPixelsPerCSSPixel in {{interface("nsIDOMWindowUtils")}} for a conversion factor to adapt to screen pixels if needed.
+
{{domxref("Window.mozInnerScreenY")}} {{ReadOnlyInline}} {{non-standard_inline}}{{gecko_minversion_inline("1.9.2")}}
+
Returns the vertical (Y) coordinate of the top-left corner of the window's viewport, in screen coordinates. This value is reported in CSS pixels. See mozScreenPixelsPerCSSPixel for a conversion factor to adapt to screen pixels if needed.
+
{{domxref("Window.mozPaintCount")}} {{non-standard_inline}}{{ReadOnlyInline}} {{gecko_minversion_inline("2.0")}}
+
Returns the number of times the current document has been rendered to the screen in this window. This can be used to compute rendering performance.
+
{{domxref("Window.name")}}
+
Gets/sets the name of the window.
+
{{domxref("Window.navigator")}} {{readOnlyInline}}
+
Returns a reference to the navigator object.
+
{{domxref("Window.opener")}}
+
Returns a reference to the window that opened this current window.
+
{{domxref("Window.outerHeight")}} {{readOnlyInline}}
+
Gets the height of the outside of the browser window.
+
{{domxref("Window.outerWidth")}} {{readOnlyInline}}
+
Gets the width of the outside of the browser window.
+
{{domxref("Window.scrollX","Window.pageXOffset")}} {{readOnlyInline}}
+
An alias for {{domxref("window.scrollX")}}.
+
{{domxref("Window.scrollY","Window.pageYOffset")}}{{readOnlyInline}}
+
An alias for {{domxref("window.scrollY")}}
+
{{domxref("Window.sessionStorage")}} {{readOnlyInline}}
+
Returns a reference to the session storage object used to store data that may only be accessed by the origin that created it.
+
{{domxref("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")}}
+
Returns a storage object for storing data within a single page session.
+
{{domxref("Window.sidebar")}} {{non-standard_inline}}{{ReadOnlyInline}}
+
Returns a reference to the window object of the sidebar.
+
{{domxref("Window.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.
+
{{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/de/web/api/window/length/index.html b/files/de/web/api/window/length/index.html new file mode 100644 index 0000000000..202c83237d --- /dev/null +++ b/files/de/web/api/window/length/index.html @@ -0,0 +1,51 @@ +--- +title: Window.length +slug: Web/API/Window/length +translation_of: Web/API/Window/length +--- +
{{ ApiRef() }}
+ +

Liefert die Anzahl an Frames ({{HTMLElement("frame")}} oder {{HTMLElement("iframe")}} elements) im aktuellen Fenster.

+ +

Syntax

+ +
framesCount = window.length;
+
+ + + +

Beispiel

+ +
if (window.length) {
+  // this is a document with subframes
+}
+ +

Spezifikationen

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG','browsers.html#dom-length','Window.length')}}{{Spec2('HTML WHATWG')}} 
{{SpecName('HTML5 W3C', 'browsers.html#dom-length', 'Window.length')}}{{Spec2('HTML5 W3C')}} 
+ +

Browserkompatibilität

+ + + +

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

diff --git a/files/de/web/api/window/localstorage/index.html b/files/de/web/api/window/localstorage/index.html new file mode 100644 index 0000000000..5395a7985f --- /dev/null +++ b/files/de/web/api/window/localstorage/index.html @@ -0,0 +1,81 @@ +--- +title: Window.localStorage +slug: Web/API/Window/localStorage +tags: + - API + - Storage + - Web Storage + - Web Storage API + - Window + - localStorage +translation_of: Web/API/Window/localStorage +--- +

{{APIRef()}}

+ +

Die localStorage-Eigenschaft erlaubt den Zugriff auf ein lokales {{domxref("Storage")}}-Objekt. localStorage ist mit einer Ausnahme identisch zu sessionStorage: Im Unterschied zu letzterem besitzen in localStorage gespeicherte Daten kein Verfallsdatum, während sie im sessionStorage mit Ablauf der session, in der Regel beim Schließen des Browsers, gelöscht werden.

+ +

localStorage und sessionStorage sind nicht nur von der Domain, sondern auch vom Protokoll abhängig, über das die Seite aufgerufen wurde. In http://example.com/ gespeicherte Daten stehen daher unter https://example.com nicht zur Verfügung.

+ +

Syntax

+ +
myStorage = localStorage;
+ +

Wert

+ +

Ein {{domxref("Storage")}}-Objekt.

+ +

Beispiel

+ +

Der folgende Ausschnitt greift auf das lokale {{domxref("Storage")}}-Objekt der aktuellen Domain zu und fügt ihm mit {{domxref("Storage.setItem()")}} einen Eintrag hinzu.

+ +
localStorage.setItem('myCat', 'Tom');
+ +

Die Syntax für das Auslesen eines Eintrages aus dem localStore lautet:

+ +
var cat = localStorage.getItem('myCat');
+ +

Die Syntax um einen Eintrag zu entfernen lautet:

+ +
localStorage.removeItem('myCat');
+ +

Die Syntax um alle Einträge zu löschen lautet:

+ +
localStorage.clear();
+ +
+

Hinweis: Ausführliche Beispiele sind im Artikel Using the Web Storage API nachzulesen.

+
+ +

Spezifikationen

+ + + + + + + + + + + + + + +
SpezifikationStatusKommentar
{{SpecName('Web Storage', '#dom-localstorage', 'localStorage')}}{{Spec2('Web Storage')}} 
+ +

Browserkompatibilität

+ + + +

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

+ +

Siehe auch

+ + diff --git a/files/de/web/api/window/name/index.html b/files/de/web/api/window/name/index.html new file mode 100644 index 0000000000..f6d3ec5b97 --- /dev/null +++ b/files/de/web/api/window/name/index.html @@ -0,0 +1,57 @@ +--- +title: Window.name +slug: Web/API/Window/name +tags: + - API +translation_of: Web/API/Window/name +--- +
{{APIRef}}
+ +

Holt oder setzt den Namen des Fensters.

+ +

Syntax

+ +
string = window.name;
+window.name = string;
+
+ +

Beispiel

+ +
window.name = "lab_view";
+
+ +

Hinweise

+ +

Der Name von Fenstern wird hauptsächlich als Ziel von Hyperlinks und Formularen verwendet. Fenster benötigen grundsätzlich keinen Namen.

+ +

window.name wurde auch in Frameworks verwendet um Domain-übergreifend zu kommunizieren (z.B. mit SessionVars oder Dojo's dojox.io.windowName) als sicherere Alternative JSONP. Moderne Webanwendungen sollten sich jedoch nicht auf window.name verlassen, sondern die postMessage API verwenden.

+ +

window.name konvertiert alle Werte zu ihre String-Repräsentation durch die Verwendung ihrer toString Methode.

+ +

Spezifikationen

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'browsers.html#dom-name', 'Window.name')}}{{Spec2('HTML WHATWG')}} 
{{SpecName('HTML5 W3C', 'browsers.html#dom-name', 'Window.name')}}{{Spec2('HTML5 W3C')}} 
+ +

Browserkompatibilität

+ + + +

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

diff --git a/files/de/web/api/window/navigator/index.html b/files/de/web/api/window/navigator/index.html new file mode 100644 index 0000000000..5e9289f088 --- /dev/null +++ b/files/de/web/api/window/navigator/index.html @@ -0,0 +1,98 @@ +--- +title: Window.navigator +slug: Web/API/Window/navigator +tags: + - API + - HTML DOM + - Property + - Read-only + - Reference + - Window +translation_of: Web/API/Window/navigator +--- +
{{APIRef}}
+ +

Die Schreibgeschützte Window.navigator Eigenschaft liefert eine Referenz des {{domxref("Navigator")}} Objekts, das Informationen über die Anwendung die das Skript ausführt liefern kann.

+ +

Syntax

+ +
navigatorObject = window.navigator
+ +

Beispiele

+ +

Beispiel #1: Browsererkennung und Ausgabe eines Texts.

+ +
var sBrowser, sUsrAg = navigator.userAgent;
+
+// The order matters here, and this may report false positives for unlisted browsers.
+
+if (sUsrAg.indexOf("Firefox") > -1) {
+  sBrowser = "Mozilla Firefox";
+  // "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:61.0) Gecko/20100101 Firefox/61.0"
+} else if (sUsrAg.indexOf("Opera") > -1 || sUsrAg.indexOf("OPR") > -1) {
+  sBrowser = "Opera";
+  //"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 OPR/57.0.3098.106"
+} else if (sUsrAg.indexOf("Trident") > -1) {
+  sBrowser = "Microsoft Internet Explorer";
+  // "Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; .NET4.0C; .NET4.0E; Zoom 3.6.0; wbx 1.0.0; rv:11.0) like Gecko"
+} else if (sUsrAg.indexOf("Edge") > -1) {
+  sBrowser = "Microsoft Edge";
+  // "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36 Edge/16.16299"
+} else if (sUsrAg.indexOf("Chrome") > -1) {
+  sBrowser = "Google Chrome or Chromium";
+  // "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/66.0.3359.181 Chrome/66.0.3359.181 Safari/537.36"
+} else if (sUsrAg.indexOf("Safari") > -1) {
+  sBrowser = "Apple Safari";
+  // "Mozilla/5.0 (iPhone; CPU iPhone OS 11_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/11.0 Mobile/15E148 Safari/604.1 980x1306"
+} else {
+  sBrowser = "unknown";
+}
+
+alert("Sie verwenden: " + sBrowser);
+ +

Beispiel #2: Browsererkennung und Rückgabe eines Index.

+ +
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());
+ +

Spezifikation

+ + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#dom-navigator', 'Window: navigator')}}{{Spec2('HTML WHATWG')}}
+  
+ +


+ Browserkompatibilität

+ + + + + +

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

diff --git a/files/de/web/api/window/ondevicemotion/index.html b/files/de/web/api/window/ondevicemotion/index.html new file mode 100644 index 0000000000..0e39638929 --- /dev/null +++ b/files/de/web/api/window/ondevicemotion/index.html @@ -0,0 +1,56 @@ +--- +title: Window.ondevicemotion +slug: Web/API/Window/ondevicemotion +tags: + - API + - Ausrichtung + - Beschleunigungssensor + - Bewegung + - Eigenschaft + - Firefox OS + - Geräteausrichtung +translation_of: Web/API/Window/ondevicemotion +--- +

{{ ApiRef() }}

+ +

Zusammenfassung

+ +

Ein Eventhandler für das {{ event("devicemotion")}} Event, welches an das Fenster gesendet wird.

+ +

Syntax

+ +
window.ondevicemotion = funcRef;
+
+ +

Die Funktion funcRef ist eine Referenz für eine Funktion. Diese Funktion erhält ein {{ domxref("DeviceMotionEvent") }} Objekt, welches die aufgetretene Bewegung beschreibt.

+ +

Spezifikationen

+ + + + + + + + + + + + + + + + +
SpezifikationStatusKommentar
{{SpecName('Device Orientation')}}{{Spec2('Device Orientation')}}Initial specification.
+ +

Browserkompatibilität

+ +

{{ page("/en-US/docs/Web/API/DeviceMotionEvent","Browser_compatibility") }}

+ +

Siehe auch

+ + diff --git a/files/de/web/api/window/opendialog/index.html b/files/de/web/api/window/opendialog/index.html new file mode 100644 index 0000000000..2dbd0587c5 --- /dev/null +++ b/files/de/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() }}

+ +

Zusammenfassung

+ +

window.openDialog ist eine Erweiterung von window.open. Es ist fast das gleiche, ausser das optional nach windowFeatures zusätzliche Parameter angegeben werden können, und windowFeatures selber wird ein bisschen anders behandelt.

+ +

Die optionalen Parameter, wenn vorhanden, werden zu einem JavaScript Array gebündelt und zum neu geöffneten Fenster hinzugefügt als eine Eigenschaft namens window.arguments. Sie können jederzeit im JavaScript des Fensters verwendet werden, auch während der ausführung eines load handler. Diese Parameter können dafür benutzt werden, um in beide Richtungen Daten mit dem Dialogfenster auszutauschen.

+ +

Beachten sie, das nach dem Aufruf von openDialog() sofort weitergefahren wird. Wenn Sie wollen, dass der Aufruf blockiert bis der Benutzer den Dialog schliesst, geben sie modal als windowFeatures Parameter an. Beachten sie, dass der Benutzer das opener window nicht bedienen kann, bis er den Dialog schliesst.

+ +

Syntax

+ +
newWindow = openDialog(url, name, features, arg1, arg2, ...)
+
+ +
+
newWindow 
+
Das geöffnete Fenster
+
url 
+
Die URL, die im neu geöffneten Fenster geladen wird.
+
name 
+
Der Name des Fensters (optional). Siehe window.open für detailierte Informationen.
+
features 
+
Siehe window.open.
+
arg1, arg2, ... 
+
Die Argumente, die dem neuen Fenster gegeben werden (optional).
+
+ +

Beispiel

+ +
var win = openDialog("http://example.tld/zzz.xul", "dlg", "", "pizza", 6.98);
+
+ +

Zu beachten

+ +

Neue Features

+ +

all - Aktiviert (oder deaktiviert ("all=no")) anfangs alles chrome (ausser die behaviour flags chrome, dialog und modal). Diese können überschrieben werden (z.B. "menubar=no,all" schaltet alles chrome ein ausser die Menüleiste.) Dieses Feature wird explizirt ignoriert von window.open. Für window.openDialog ist es nützlich wegen unterschiedlichem Standardverhalten.

+ +

Standardverhalten

+ +

Die window Features chrome und dialog  sind immer eingeschaltet, ausser sie werden explizit ausgeschaltet ("chrome=no"). openDialog behandelt einen nicht vorhandenen features Parameter gleich wie window.open, (ein leerer String schaltet alle Features aus) ausser chrome und dialog, welche standartmässig eingeschaltet sind. Wenn der features Parameter ein leerer String ist, oder nur behaviour features (chrome, dependent, dialog und modal) enthält, werden die chrome features nach der "OS' choice" ausgewählt. Das heisst, der window creation code erhält keine spezifischen Anweisungen, kann dafür das chrome auswählen, das am besten zu einem Dialog auf diesem operating system passt.

+ +

Zusätzliche Parameter zum Dialog hinzufügen

+ +

Um dem Fenster zusätzliche Parameter hinzuzufügen, können Sie diese einfach nach dem windowFeatures parameter einfügen:

+ +
openDialog("http://example.tld/zzz.xul", "dlg", "", "pizza", 6.98);
+
+ +

Die zusätzlichen Parameter werden dann in eine Eigenschaft gepackt namens arguments mit dem Typ Array, und diese Eigenschaft wird dem neu erzeugten Fenster hinzugefügt.

+ +

Benützen Sie dieses Schema, um im Code des Dialogs auf diese zusätzlichen Parameter zuzugreifen:

+ +
var food  = window.arguments[0];
+var price = window.arguments[1];
+
+ +

Beachten Sie, dass Sie überall im Code des Dialogs auf diese Eigenschaft zugreiffen können. (Anderes Beispiel).

+ +

Werte vom Dialog zurückerhalten

+ +

Weil window.close() alle Eigenschaften des Dialogfensters löscht (d.h. die Variablen vom JavaScript des Dialogs), ist es nicht möglich, mit globalen Variablen (oder anderen Konstrukten) nach dem Schliessen Werte zurückzugeben.

+ +

Um Werte zum Aufrufer zurückzugeben, müssen Sie ein Objekt mit den zusätzlichen Parametern übergeben. Sie können im Code des Dialogs auf dieses Objekt zugreiffen und Eigenschaften setzen, welche die Werte enthalten, die Sie zurückgeben wollen oder die Sie auch nach window.close() behalten wollen.

+ +
var retVals = { address: null, delivery: null };
+openDialog("http://example.tld/zzz.xul", "dlg", "modal", "pizza", 6.98, retVals);
+
+ +

Wenn Sie im Dialog die Eigenschaften von retVals im Code des Dialogs setzen wie unten beschrieben, können Sie über retVals auf sie zugreiffen nach dem der Aufruf von openDialog() zurückkommt.

+ +

Im JavaScript des Dialogs können Sie wie folgt auf die Eigenschaften zugreiffen:

+ +
var retVals = window.arguments[2];
+retVals.address  = enteredAddress;
+retVals.delivery = "immediate";
+
+ +

Siehe auch hier. (anderes Beispiel).
+ Siehe auch window.importDialog (mobile).

+ +

Spezifikation

+ +

{{ DOM0() }}

diff --git a/files/de/web/api/window/opener/index.html b/files/de/web/api/window/opener/index.html new file mode 100644 index 0000000000..32301159ce --- /dev/null +++ b/files/de/web/api/window/opener/index.html @@ -0,0 +1,28 @@ +--- +title: Window.opener +slug: Web/API/Window/opener +translation_of: Web/API/Window/opener +--- +
{{APIRef}}
+ +

Zusammenfassung

+ +

Gibt einen Hinweis auf das Fenster, welches das aktuelle Fenster öffnete.

+ +

Schreibweise

+ +
objRef = window.opener;
+
+ +

Beispiel

+ +
if (window.opener != indexWin) {
+  referToTop(window.opener);
+}
+
+ +

Bemerkungen

+ +

Öffnet man ein Fenster aus einem anderen Fenster heraus (mittels {{domxref("Window.open")}} oder target='_blank'), wird im neuen Fenster ein Bezug auf das ursprüngliche Fenster mit window.opener aufrecht erhalten. Wurde das aktuelle Fenster nicht aus einem anderen Fenster geöffnet, wird NULL ausgegeben.

+ +

Der Browser in Windows Smartphones unterstützt window.opener nicht (getestet mit Microsoft Edge 25.10586.36.0). Auch im Internet Explorer gibt es keine Unterstützung, wenn die Aktivität von einer anderen Sicherheitszone ausgeht.

diff --git a/files/de/web/api/window/performance/index.html b/files/de/web/api/window/performance/index.html new file mode 100644 index 0000000000..7805b7b019 --- /dev/null +++ b/files/de/web/api/window/performance/index.html @@ -0,0 +1,96 @@ +--- +title: Window.performance +slug: Web/API/Window/performance +tags: + - Performanz + - Timing +translation_of: Web/API/Window/performance +--- +
{{APIRef("High Resolution Time")}}
+ +

Die Eigenschaft performance der {{domxref("Window")}} Schnittstelle  gibt ein {{domxref("Performance")}} Objekt zurück, welches benutzt werden kann, um Performanz-Informationen über das aktuelle Dokument zu sammeln. Sie dient als Bereitstellungspunkt für die Performance Timeline API, die High Resolution Time API, die Navigation Timing API, die User Timing API, und die Resource Timing API.

+ +

Syntax

+ +
performanceData = window.performance;
+ +

Wert

+ +

Ein {{domxref("Performance")}}-Objekt bietet Zugriff auf Performanz- und Timing-Informationen, die von den APIs, welche es offen legt, bereit gestellt werden.

+ +

Spezifikationen

+ + + + + + + + + + + + + + +
SpecifikationStatusKommentar
{{SpecName('Highres Time', '#the-performance-interface', 'window.performance')}}{{Spec2('Highres Time')}}Definiert die now() Methode.
+ +

Browserkompabilität

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Grundsätzliche Unterstützung6.0{{CompatVersionUnknown}}{{CompatGeckoDesktop("7.0")}}9.015.08
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewEdgeFirefox Mobile (Gecko)IE PhoneOpera MobileSafari MobileChrome for Android
Grundsätzliche Unterstützung{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("7.0")}}9.015.09{{CompatVersionUnknown}}
+
+ +

 

diff --git a/files/de/web/api/window/print/index.html b/files/de/web/api/window/print/index.html new file mode 100644 index 0000000000..3043194293 --- /dev/null +++ b/files/de/web/api/window/print/index.html @@ -0,0 +1,50 @@ +--- +title: Window.print() +slug: Web/API/Window/print +translation_of: Web/API/Window/print +--- +

{{ ApiRef() }}

+ +

Öffnet den Dialog zum Drucken des aktuellen Dokuments.

+ +

In den meisten Browsern wird die Methode nicht ausgeführt, sofern bereits ein Druck-Dialog geöffnet ist.

+ +

Syntax

+ +
window.print()
+
+ +

Anmerkungen

+ +

Seit Chrome Version {{CompatChrome(46.0)}} wird diese Methode innerhalb eines {{htmlelement("iframe")}} Elements blockiert, solange kein sandbox Attribut mit dem Wert allow-modal gesetzt ist.

+ +

Spezifikation

+ + + + + + + + + + + + + + +
SpezifikationStatusKommentare
{{SpecName('HTML5 Web application', '#dom-print', 'print()')}}{{Spec2('HTML5 Web application')}}Erste Definition.
+ +

Browserkompatibilität

+ +

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

+ +

Siehe auch

+ + + +

{{ languages( { "ja": "ja/DOM/window.print", "it": "it/DOM/window.print" , "zh-cn": "zh-cn/DOM/window.print" } ) }}

diff --git a/files/de/web/api/window/prompt/index.html b/files/de/web/api/window/prompt/index.html new file mode 100644 index 0000000000..5fe0290c4e --- /dev/null +++ b/files/de/web/api/window/prompt/index.html @@ -0,0 +1,79 @@ +--- +title: Window.prompt() +slug: Web/API/Window/prompt +translation_of: Web/API/Window/prompt +--- +
{{ApiRef("Window")}}
+ +

Window.prompt() zeigt ein Dialogfenster mit einem Text-Eingabefeld an, mit einer optionalen Nachricht an den Benutzer.

+ +

Syntax

+ +
eingabe = window.prompt(nachricht, default);
+
+ + + +

Beispiel

+ +
var sign = prompt("What's your sign?");
+
+if (sign.toLowerCase() == "scorpio") {
+  alert("Wow! I'm a Scorpio too!");
+}
+
+// es gibt viele Möglichkeiten, um die prompt-Funktion zu nutzen
+var sign = window.prompt(); //  Öffnet das leere Eingabefenster 
+var sign = prompt();       //   Öffnet das leere Eingabefenster
+var sign = window.prompt('Are you feeling lucky'); // Öffnet das Eingabefenster mit dem Text "Are you feeling lucky"
+var sign = window.prompt('Are you feeling lucky', 'sure'); // Öffnet das Eingabefenster mit dem Text "Are you feeling lucky" und dem Standardwert "sure"
+ +

Wenn der Benutzer den OK-Button drückt, wird der Text im Eingabefeld zurückgegeben. Falls das Feld leer ist, wenn der Benutzer den OK-Button drückt, wird ein leerer String zurückgegeben. Wird der Abbrechen-Button gedrückt, gibt die Funktion null zurück.

+ +

Die obige Eingabeaufforderung wird wie folgt angezeigt (in Chrome auf OS X):

+ +

prompt() dialog in Chrome on OS X

+ +

Anmerkungen

+ +

Ein prompt-Dialogfenster einen einzeiligen Text, einen Abbrechen-Button und einen OK-Button und gibt den (möglicherweise leeren) Text zurück, der ins Textfeld eingegeben wurde.

+ +

The following text is shared between this article, DOM:window.confirm and DOM:window.alert Dialogfenster sind modal - sie verhindern, dass der Anwender auf den Rest der Seite zugreifen kann, bis das Dialogfenster geschlossen wurde. Aus diesen Grund sollte man Funktionen, die Dialogfenster anzeigen, nicht zu oft verwenden.

+ +

Beachte, dass ein String zurückgegeben wird. Das heißt, die Eingabe muss manchmal gecasted werden. Beispiel: Falls eine Zahl eingegeben werden soll, sollte der String zu einer Zahl gecasted werden. var aNumber = Number(window.prompt("Gib eine Zahl ein", ""));

+ +

Mozilla Chrome-Nutzer (z.B. Firefox-Erweiterungen) sollten stattdessen {{interface("nsIPromptService")}} verwenden.

+ +

Seit Chrome {{CompatChrome(46.0)}} wird diese Funktion innerhalb eines {{htmlelement("iframe")}}s blockiert, es sei denn, dessen sandbox-Attribut hat den Wert allow-modal.

+ +

In Safari wird auch dann ein leerer String zurückgegeben, wenn Abbrechen gedrückt wurde. Es macht also keinen Unterschied, ob OK oder Abbrechen gedrückt wird, wenn das Eingabefeld leer ist.

+ +

Diese Funktion hat keinen Effekt in der Modern UI/Metro-Version von Internet Explorer für Windows 8. Es zeigt kein Dialogfenster an und gibt immer undefined zurück. Es ist unklar, ob dieses Verhalten Absicht oder ein Bug ist. Desktopversionen von Internet Explorer implementieren die Funktion aber.

+ +

Spezifikationen

+ + + + + + + + + + + + + + +
SpezifikationenStatusKommentar
{{SpecName('HTML5 Web application', '#dom-prompt', 'prompt()')}}{{Spec2('HTML5 Web application')}}Anfängliche Definition.
+ +

Siehe auch

+ + diff --git a/files/de/web/api/window/screenx/index.html b/files/de/web/api/window/screenx/index.html new file mode 100644 index 0000000000..61221ffd18 --- /dev/null +++ b/files/de/web/api/window/screenx/index.html @@ -0,0 +1,98 @@ +--- +title: Window.screenX +slug: Web/API/Window/screenX +translation_of: Web/API/Window/screenX +--- +
{{APIRef}}
+ +
Die schreibgeschützte Eigenschaft Window.screenX liefert den Abstand in CSS-Pixeln zwischen dem linken Bildschirmrand und dem linken Rand des Browsers.
+ +
 
+ +

Syntax

+ +
lLoc = window.screenX
+
+ + + +

Spezifikationen

+ + + + + + + + + + + + + + + + +
SpezifikationStatusKommentar
{{ SpecName('CSSOM View', '#dom-window-screenx', 'Window.screenX') }}{{ Spec2('CSSOM View') }}Initiale Definition.
+ +

Browserkompatibilität

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }} [1]{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }} [1]{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +

[1] Vor Firefox 28 nutzte Gecko "device pixel" anstatt CSS-Pixel; anders gesagt nahm es für den Wert von screenPixelsPerCSSPixel für jedes Gerät "1" an.

+ +

Siehe auch

+ + diff --git a/files/de/web/api/window/scroll/index.html b/files/de/web/api/window/scroll/index.html new file mode 100644 index 0000000000..95f7da74fc --- /dev/null +++ b/files/de/web/api/window/scroll/index.html @@ -0,0 +1,56 @@ +--- +title: Window.scroll() +slug: Web/API/Window/scroll +translation_of: Web/API/Window/scroll +--- +
{{APIRef}}
+ +

Zusammenfassung

+ +

Scrollt das Fenster zu einer bestimmten Stelle im Dokument.

+ +

Syntax

+ +
window.scroll(x-koord,y-koord)
+
+ +

Parameters

+ + + +

Beispiel

+ +
<!-- lege den 100. vertikalen Pixel an der oberen Fensterrand -->
+
+<button onClick="scroll(0, 100);">Klicken, um 100 Pixel nach unten zu scrollen</button>
+
+ +

Notizen

+ +

window.scrollTo ist praktisch dasselbe wie diese Methode. Zum wiederholten Blättern um einen bestimmten Abstand, wird window.scrollBy benutzt. Siehe auch window.scrollByLines, window.scrollByPages.

+ +

Spezifikation

+ +
+
+ + + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('CSSOM View', '#dom-window-scrollto', 'window.scrollTo()') }}{{ Spec2('CSSOM View') }}Erste Definition.
+
+
diff --git a/files/de/web/api/window/scrollto/index.html b/files/de/web/api/window/scrollto/index.html new file mode 100644 index 0000000000..c33f70df89 --- /dev/null +++ b/files/de/web/api/window/scrollto/index.html @@ -0,0 +1,75 @@ +--- +title: Window.scrollTo() +slug: Web/API/Window/scrollTo +tags: + - API + - Méthode + - Referenz +translation_of: Web/API/Window/scrollTo +--- +
{{ APIRef }}
+ +

Window.scrollTo() scrollt zu einer spezifischen Koordinate im Dokument.

+ +

Syntax

+ +
window.scrollTo(x-Koordinate, y-Koordinate)
+window.scrollTo(options)
+
+ +

Parameter

+ + + +

- or -

+ + + +

Beispiele

+ +
window.scrollTo(0, 1000);
+
+ +

Mit Benutzung von options:

+ +
window.scrollTo({
+  top: 100,
+  left: 100,
+  behavior: 'smooth'
+});
+ +

Anmerkungen

+ +

{{domxref("Window.scroll()")}} ist im Endeffekt die gleiche Methode. Schau dir {{domxref("Window.scrollBy()")}}, {{domxref("Window.scrollByLines()")}}, und {{domxref("Window.scrollByPages()")}} für relatives scrollen an.

+ +

Um Elemente zu scrollen, schau dir {{domxref("Element.scrollTop")}} und {{domxref("Element.scrollLeft")}} an.

+ +

Spezifikationen

+ + + + + + + + + + + + + + + + +
SpezifikationStatusKommentar
{{ SpecName('CSSOM View', '#dom-window-scroll', 'window.scroll()') }}{{ Spec2('CSSOM View') }}Anfängliche Definition.
+ +

Browser Kompatibilität

+ + + +

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

diff --git a/files/de/web/api/window/sessionstorage/index.html b/files/de/web/api/window/sessionstorage/index.html new file mode 100644 index 0000000000..b5adca4a81 --- /dev/null +++ b/files/de/web/api/window/sessionstorage/index.html @@ -0,0 +1,90 @@ +--- +title: Window.sessionStorage +slug: Web/API/Window/sessionStorage +tags: + - API + - Property + - Storage +translation_of: Web/API/Window/sessionStorage +--- +

{{APIRef()}}

+ +

Die sessionStorage-Eigenschaft erlaubt den Zugriff auf ein nur während der aktuellen Sitzung verfügbares Storage-Objekt. sessionStorage ist mit einer Ausnahme identisch zu {{domxref("Window.localStorage")}}: In localStorage gespeicherte Daten besitzen kein Verfallsdatum, während sie im sessionStorage mit Ablauf der Sitzung gelöscht werden. Eine Sitzung endet erst mit dem Schließen des Browsers, sie übersteht das Neuladen und Wiederherstellen einer Webseite. Das Öffnen einer Webseite in einem neuen Tab oder Browserfenster erzeugt jedoch eine neue Sitzung; ein Unterschied zur Funktionsweise von Session-Cookies.

+ +

localStorage und sessionStorage sind nicht nur von der Domain, sondern auch vom Protokoll abhängig, über das die Seite aufgerufen wurde. In http://example.com/ gespeicherte Daten stehen daher unter https://example.com nicht zur Verfügung.

+ +

Syntax

+ +
// Daten im sessionStorage speichern
+sessionStorage.setItem('key', 'value');
+
+// Gespeicherte Daten aus dem sessionStorage abfragen
+var data = sessionStorage.getItem('key');
+
+// Gespeicherte Daten aus dem sessionStorage entfernen
+sessionStorage.removeItem('key');
+
+// Alle gespeicherten Daten aus dem sessionStorage entfernen
+sessionStorage.clear(); 
+ +

Wert

+ +

Ein {{domxref("Storage")}}-Objekt.

+ +

Beispiel

+ +

Im folgenden Beispiel wird auf das sessionStorage-Objekt der aktuellen Domain zugegriffen und mit {{domxref("Storage.setItem()")}} Daten hinzugefügt:

+ +
sessionStorage.setItem('myCat', 'Tom');
+ +

Das folgende Beispiel speichert automatisch den Inhalt eines Textfeldes. Bei einem versehentlichen Neuladen der Seite wird der Inhalt wiederhergestellt, sodass keine Eingaben verloren gehen.

+ +
// Das Textfeld holen, das überwacht werden soll
+var field = document.getElementById("field");
+
+// Prüfen, ob ein gespeicherter Wert vorliegt
+// (das ist nur dann der Fall, wenn die Seite versehentlich aktualisiert wurde)
+if (sessionStorage.getItem("autosave")) {
+  // Den Inhalt des Testfeldes aus dem sessionStorage wiederherstellen
+  field.value = sessionStorage.getItem("autosave");
+}
+
+// Änderungen des Inhalts des Textfeldes überwachen
+field.addEventListener("change", function() {
+  // Speichern des Inhalts des Textfeldes im sessionStorage
+  sessionStorage.setItem("autosave", field.value);
+});
+ +
+

Anmerkung: Ein vollständiges Beispiel kann unter Using the Web Storage API nachgelesen werden.

+
+ +

Spezifikationen

+ + + + + + + + + + + + + + +
SpezifikationStatusBemerkung
{{SpecName('Web Storage', '#the-sessionstorage-attribute', 'sessionStorage')}}{{Spec2('Web Storage')}} 
+ +

Browserkompatibilität

+ + + +

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

+ +

Siehe auch

+ + diff --git a/files/de/web/api/window/stop/index.html b/files/de/web/api/window/stop/index.html new file mode 100644 index 0000000000..8968e89177 --- /dev/null +++ b/files/de/web/api/window/stop/index.html @@ -0,0 +1,38 @@ +--- +title: Window.stop() +slug: Web/API/Window/stop +tags: + - API + - DOM + - DOM_0 + - Method + - stopwindowloading +translation_of: Web/API/Window/stop +--- +
{{APIRef}}
+ +

Zusammenfassung

+ +

Diese Methode stoppt das Laden des Fensters.

+ +

Syntax

+ +
window.stop()
+
+ +

Beispiel

+ +
window.stop();
+
+ +

Notizen

+ +

Die stop() Methode ist genau equivalent zum Klicken des Stop-Buttons im Browser. Aufgrund der Reihenfolge in der Scripte geladen werden, kann die stop() Methode nicht das Dokument, in dem es enthalten ist, vom Laden stoppen, aber es stoppt das Laden von großen Bildern, neuen Fenstern, und anderen Objekten, die verzögert geladen werden.

+ +

Spezifikation

+ +

DOM Level 0. Kein Teil der Spezifikation.

+ +

Compatibility

+ +

Die stop() Methode wird nicht vom Internet Explorer unterstützt.

diff --git a/files/de/web/api/windowbase64/btoa/index.html b/files/de/web/api/windowbase64/btoa/index.html new file mode 100644 index 0000000000..9d980c340a --- /dev/null +++ b/files/de/web/api/windowbase64/btoa/index.html @@ -0,0 +1,145 @@ +--- +title: WindowBase64.btoa() +slug: Web/API/WindowBase64/btoa +tags: + - API + - Méthode + - Referenz +translation_of: Web/API/WindowOrWorkerGlobalScope/btoa +--- +
{{APIRef("HTML DOM")}}
+ +

Erzeugt eine Base-64-kodierten ASCII-Zeichenkette aus einer "Zeichenkette" von Binärdaten.

+ +

Hinweis: diese Funktion ist nicht für Raw-Unicode-Zeichenketten geeignet (siehe Abschnitt "Unicode-Zeichenketten" unten).

+ +

Syntax

+ +
var encodedData = window.btoa(stringToEncode);
+ +

Example

+ +
var encodedData = window.btoa("Hello, world"); // Zeichenkette kodieren
+var decodedData = window.atob(encodedData); // Zeichenkette dekodieren
+
+ +

Hinweise

+ +

Diese Methode kann verwendet werden, um Daten zu kodieren, übertragen, und mittels {{domxref("WindowBase64.atob","window.atob()")}} wieder zu dekodieren, welche andernfalls Übertragungsprobleme bereiten würden. Beispielsweise ist es möglich, die Steuerzeichen mit den ASCII-Werten 0 bis 31 zu kodieren.

+ +

btoa() steht auch in JavaScript implementierten XPCOM-Komponenten zur Verfügung, auch wenn window in solchen Komponenten nicht das globale Objekt ist.

+ +

Unicode-Zeichenketten

+ +

In den meisten Browsern verursacht ein Aufruf von window.btoa() mit einer Unicode-Zeichenkette eine "Character Out Of Range"-Exception ("Zeichen außerhalb des zulässigen Wertebereichs").

+ +

Das kann mithilfe eines solchen Code-Schemas vermieden werden (beigesteuert von Johan Sundström):

+ +
function utf8_to_b64(str) {
+    return window.btoa(unescape(encodeURIComponent(str)));
+}
+
+function b64_to_utf8(str) {
+    return decodeURIComponent(escape(window.atob(str)));
+}
+
+// Usage:
+utf8_to_b64('✓ à la mode'); // JTI1dTI3MTMlMjUyMCUyNUUwJTI1MjBsYSUyNTIwbW9kZQ==
+b64_to_utf8('JTI1dTI3MTMlMjUyMCUyNUUwJTI1MjBsYSUyNTIwbW9kZQ=='); // "✓ à la mode"
+
+utf8_to_b64('I \u2661 Unicode!'); // SSUyNTIwJTI1dTI2NjElMjUyMFVuaWNvZGUlMjUyMQ==
+b64_to_utf8('SSUyNTIwJTI1dTI2NjElMjUyMFVuaWNvZGUlMjUyMQ=='); // "I ♡ Unicode!"
+
+
+ +

Eine günstigere, zuverlässigere und effizientere Lösung ist, DOMString zunächst in eine UTF-8-kodierte Zeichenkette zu konvertieren, die sich für typed arrays eignet. Eine Anleitung bietet dieser Abschnitt.

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#dom-windowbase64-btoa', 'WindowBase64.btoa()')}}{{Spec2('HTML WHATWG')}}No change since the latest snapshot, {{SpecName("HTML5.1")}}.
{{SpecName('HTML5.1', '#dom-windowbase64-btoa', 'WindowBase64.btoa()')}}{{Spec2('HTML5.1')}}Snapshot of {{SpecName("HTML WHATWG")}}. No change.
{{SpecName("HTML5 W3C", "#dom-windowbase64-btoa", "WindowBase64.btoa()")}}{{Spec2('HTML5 W3C')}}Snapshot of {{SpecName("HTML WHATWG")}}. Creation of WindowBase64 (properties where on the target before it).
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatVersionUnknown}}{{CompatGeckoDesktop(1)}}[1]10{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatGeckoMobile(1)}}{{CompatNo}}{{CompatUnknown}}{{CompatVersionUnknown}}
+
+ +

[1] btoa() is also available to XPCOM components implemented in JavaScript, even though window is not the global object in components.

+ +

See also

+ + diff --git a/files/de/web/api/windowbase64/index.html b/files/de/web/api/windowbase64/index.html new file mode 100644 index 0000000000..40051820b4 --- /dev/null +++ b/files/de/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/de/web/api/windoweventhandlers/index.html b/files/de/web/api/windoweventhandlers/index.html new file mode 100644 index 0000000000..cdd4a8258b --- /dev/null +++ b/files/de/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 describes the event handlers common to several interfaces like {{domxref("Window")}}, or {{domxref("HTMLBodyElement")}} and  {{domxref("HTMLFrameSetElement")}}. Each of these interfaces can implement more event handlers.

+ +

WindowEventHandlers is a 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("WindowEventHandlers")}}, and implemented by {{domxref("Window")}}, and {{domxref("WorkerGlobalScope")}} for Web Workers.

+ +
+
{{domxref("WindowEventHandlers.onafterprint")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("afterprint")}} event is raised.
+
{{domxref("WindowEventHandlers.onbeforeprint")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("beforeprint")}} event is raised.
+
{{domxref("WindowEventHandlers.onbeforeunload")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("beforeunload")}} event is raised.
+
{{domxref("WindowEventHandlers.onhashchange")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("hashchange")}} event is raised.
+
{{domxref("WindowEventHandlers.onlanguagechange")}} {{experimental_inline}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("languagechange")}} event is raised.
+
{{domxref("WindowEventHandlers.onmessage")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("message")}} event is raised.
+
{{domxref("WindowEventHandlers.onoffline")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("offline")}} event is raised.
+
{{domxref("WindowEventHandlers.ononline")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("online")}} event is raised.
+
{{domxref("WindowEventHandlers.onpagehide")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("pagehide")}} event is raised.
+
{{domxref("WindowEventHandlers.onpageshow")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("pageshow")}} event is raised.
+
{{domxref("WindowEventHandlers.onpopstate")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("popstate")}} event is raised.
+
{{domxref("WindowEventHandlers.onresize")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("resize")}} event is raised.
+
{{domxref("WindowEventHandlers.onstorage")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("storage")}} event is raised.
+
{{domxref("WindowEventHandlers.onunload")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("unload")}} event is raised.
+
+ +

Methods

+ +

This interface defines no method.

+ +

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

See also

+ + diff --git a/files/de/web/api/windoweventhandlers/onafterprint/index.html b/files/de/web/api/windoweventhandlers/onafterprint/index.html new file mode 100644 index 0000000000..088f6c91aa --- /dev/null +++ b/files/de/web/api/windoweventhandlers/onafterprint/index.html @@ -0,0 +1,93 @@ +--- +title: WindowEventHandlers.onafterprint +slug: Web/API/WindowEventHandlers/onafterprint +translation_of: Web/API/WindowEventHandlers/onafterprint +--- +
{{ApiRef}}
+ +
Die Eigenschaft WindowEventHandlers.onafterprint definiert und gibt den {{event("onafterprint")}} {{domxref("EventHandler")}} für das aktuelle Window aus.
+ +

Syntax

+ +
window.onafterprint = event handling code
+
+ +

Beschreibung

+ +

Manche Browser (inklusive Firefox 6 und neuer, Internet Explorer) senden beforeprint und afterprint Events um zu bestimmen, ob ein Druckvorgang stattgefunden hat. Diese Funktion kann genutzt werden um das User-Interface während des Druckvorgangs anzupassen (z.B das Ausblenden von User-Interface Elementen während des Druckvorgangs).

+ +

Das afterprint Event wird ausgelöst nachdem der Nutzer gedruckt hat oder den den Druck abgebrochen hat.

+ +

Spezifikation

+ +

Nicht Teil einer Spezifikation.

+ +

Browserkompatbilität

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatNo}}6.0{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

Siehe auch

+ + + +
 
diff --git a/files/de/web/api/windoweventhandlers/onhashchange/index.html b/files/de/web/api/windoweventhandlers/onhashchange/index.html new file mode 100644 index 0000000000..3bb0fb12a9 --- /dev/null +++ b/files/de/web/api/windoweventhandlers/onhashchange/index.html @@ -0,0 +1,162 @@ +--- +title: WindowEventHandlers.onhashchange +slug: Web/API/WindowEventHandlers/onhashchange +tags: + - Eigenschaft + - Event + - HTML-DOM + - Referenz + - WindowEventHandlers +translation_of: Web/API/WindowEventHandlers/onhashchange +--- +
+
{{APIRef("HTML DOM")}}
+
+ +

Das hashchange Event wird ausgelöst wenn sich der window.hash verändert (siehe {{domxref("Window.location", "location.hash")}}).

+ +

Syntax

+ +
window.onhashchange = funcRef;
+
+ +

oder

+ +
<body onhashchange="funcRef();">
+
+ +

oder

+ +
window.addEventListener("hashchange", funcRef, false);
+
+ +

Parameter

+ +
+
funcRef
+
Ein Verweis auf eine Funktion.
+
+ +

Beispiel

+ +
if ("onhashchange" in window) {
+    alert("Der Browser unterstützt das hashchange-Event!");
+}
+
+function locationHashChanged() {
+    if (location.hash === "#irgendeinCoolesFeature") {
+        featureFunction();
+    }
+}
+
+window.onhashchange = locationHashChanged;
+
+ +

Das hashchange Event

+ +

Das ausgelöste hashchange Event hat folgende Eigenschaften:

+ + + + + + + + + + + + + + + + + + + +
EigenschaftTypBeschreibung
newURL {{gecko_minversion_inline("6.0")}}DOMStringDie neue URL zu der das Fenster nun navigiert.
oldURL {{gecko_minversion_inline("6.0")}}DOMStringDie vorherige URL, von der aus das Fenster navigierte.
+ + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#windoweventhandlers', 'GlobalEventHandlers')}}{{Spec2('HTML WHATWG')}} 
{{SpecName('HTML5.1', '#windoweventhandlers', 'GlobalEventHandlers')}}{{Spec2('HTML5.1')}} 
{{SpecName("HTML5 W3C", "#windoweventhandlers", "GlobalEventHandlers")}}{{Spec2('HTML5 W3C')}} 
+ +

Browser-Kompatiblität

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support5.0{{CompatGeckoDesktop("1.9.2")}} +

8.0

+ +

oldURL/newURL Eigenschaften werden nicht unterstützt.

+
10.65.0
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support2.2{{CompatGeckoMobile("1.9.2")}}9.011.05.0
+
+ + diff --git a/files/de/web/api/windoweventhandlers/onpopstate/index.html b/files/de/web/api/windoweventhandlers/onpopstate/index.html new file mode 100644 index 0000000000..5154919751 --- /dev/null +++ b/files/de/web/api/windoweventhandlers/onpopstate/index.html @@ -0,0 +1,57 @@ +--- +title: WindowEventHandlers.onpopstate +slug: Web/API/WindowEventHandlers/onpopstate +translation_of: Web/API/WindowEventHandlers/onpopstate +--- +
{{APIRef}} {{gecko_minversion_header("2")}}
+ +

Zusammenfassung

+ +

Hier geht es um die Ereignisbehandlungsroutine, üblicherweise event handler genannt, für das popstate Ereignis (event) des window Objekts.

+ +

Ein popstate Ereignis wird an window übermittelt, wann immer der aktive history Eintrag zwischen zwei Einträgen für dasselbe Dokument wechselt. Falls der zu aktivierende history Eintrag erzeugt wurde durch den Aufruf von history.pushState() oder beeinflusst wurde durch Aufruf von history.replaceState(), dann enthält die state Eigenschaft des popstate Ereignisses eine Kopie des state Objekts des history Eintrags. 

+ +

Es gilt zu beachten, dass der bloße Aufruf von history.pushState() oder history.replaceState() kein popstate Ereignis auslöst. Das popstate Ereignis wird allein durch Anklicken des Zurück-Buttons (oder den Aufruf von history.back() per Javascript) ausgelöst. Auch wird das Ereignis nur ausgelöst, wenn sich der Anwender zwischen zwei history Einträgen für dasselbe Dokument bewegt.

+ +

Browser behandeln den popstate Zustand nach initialem Laden einer Seite (onload) auf verschiedene Weise. Chrome (vor Version 34) und Safari senden immer ein popstate Ereignis, Firefox hingegen nicht.

+ +

Syntax

+ +
window.onpopstate = funcRef;
+
+ + + +

Das popstate Ereignis

+ +

Zum Beispiel würde eine Seite mit der URL http://example.com/example.html beim Durchlaufen dieses Codes die folgenden Meldungen in der Konsole ausgeben:

+ +
window.onpopstate = function(event) {
+  alert("location: " + document.location + ", state: " + JSON.stringify(event.state));
+};
+
+history.pushState({page: 1}, "title 1", "?page=1");
+history.pushState({page: 2}, "title 2", "?page=2");
+history.replaceState({page: 3}, "title 3", "?page=3");
+history.back(); // alerts "location: http://example.com/example.html?page=1, state: {"page":1}"
+history.back(); // alerts "location: http://example.com/example.html, state: null
+history.go(2);  // alerts "location: http://example.com/example.html?page=3, state: {"page":3}
+
+ +

Obwohl mit dem ursprünglichen history Eintrag (für die URL http://example.com/example.html) kein state Objekt verknüpft ist, wird dennoch ein popstate Ereignis ausgelöst, sobald dieser Eintrag durch den zweiten Aufruf von history.back() aktiv wird.

+ +

Spezifikation

+ + + +

Weiterführende Informationen

+ + diff --git a/files/de/web/api/windowtimers/index.html b/files/de/web/api/windowtimers/index.html new file mode 100644 index 0000000000..396aca3d4d --- /dev/null +++ b/files/de/web/api/windowtimers/index.html @@ -0,0 +1,124 @@ +--- +title: WindowTimers +slug: Web/API/WindowTimers +tags: + - API + - HTML-DOM + - Interface + - NeedsTranslation + - Reference + - TopicStub + - Workers +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/de/web/api/windowtimers/settimeout/index.html b/files/de/web/api/windowtimers/settimeout/index.html new file mode 100644 index 0000000000..9f13870d78 --- /dev/null +++ b/files/de/web/api/windowtimers/settimeout/index.html @@ -0,0 +1,329 @@ +--- +title: WindowTimers.setTimeout() +slug: Web/API/WindowTimers/setTimeout +translation_of: Web/API/WindowOrWorkerGlobalScope/setTimeout +--- +
{{APIRef("HTML DOM")}}
+ +

Die Funktion setTimeout() der {{domxref("WindowOrWorkerGlobalScope")}}-Schnittstelle ruft nach der gegebenen Zeitspanne eine Funktion oder direkt angebenen Code auf.

+ +

Syntax

+ +
var timeoutID = window.setTimeout(funktion, zeitspanne, [parameter1, parameter2, ...]);
+var timeoutID = window.setTimeout(code, zeitspanne);
+
+ +

 

+ +

Parameter

+ +

 

+ +
+
funktion
+
Die {{jsxref("function", "Funktion")}}, die nach zeitspanne Millisekunden ausgeführt werden soll.
+
code
+
code in der alternativen Syntax ist eine Zeichenkette, die Code enthält, der nach zeitspanne Millisekunden ausgeführt werden soll.  code sollte aus den gleichen Gründen, die auch eval() zum Sicherheitsrisiko machen, nicht verwendet werden.
+
zeitspanne {{optional_inline}}
+
zeitspanne ist die Wartezeit in Millisekunden (ein Tausendstel einer Sekunde), nach der funktion bzw. code ausgeführt werden soll. Dieser Wert ist ein Mindestwert, die tatsächlich abgelaufene Zeit kann länger sein, siehe {{anch("Gründe für längere als gegebene Wartezeiten")}} weiter unten.
+
parameter1, ..., parameterN {{optional_inline}}
+
Diese Parameter werden an die funktion oder den code übergeben.
+
+ +
Anmerkung: Der Internet Explorer unterstützt bis einschließlich Version 9 die Übergabe von zusätzlichen Parametern nicht.
+ +

Rückgabewert

+ +

setTimeout() gibt eine ID zurück, die den eingerichteten Zeitgeber identifiziert; um die Wartezeit abzubrechen, kann sie an {{domxref("WindowOrWorkerGlobalScope.clearTimeout","clearTimeout()")}}  übergeben werden.

+ +

Jede ID wird von setTimeout() und setInterval() nur einmalig je Objekt (window oder Worker) verwendet.

+ +

Beispiel

+ +

HTML

+ +
<p>Beispiel</p>
+<button onclick="delayedAlert();">Zeige nach zwei Sekunden einen Alarm.</button>
+<p></p>
+<button onclick="clearAlert();">Alarm vorzeitig abbrechen.</button>
+ +

JavaScript

+ +
var timeoutID;
+
+function delayedAlert() {
+  timeoutID = window.setTimeout(slowAlert, 2000);
+}
+
+function slowAlert() {
+  alert('Das hat gedauert!');
+}
+
+function clearAlert() {
+  window.clearTimeout(timeoutID);
+}
+ +

Ergebnis

+ +

{{EmbedLiveSample('Example')}}

+ +

Siehe auch clearTimeout()

+ +

Polyfill

+ +

Der nachfolgende Polyfill-Code ermöglicht es, der aufzurufenden Funktion auch im Internet Explorer Parameter zu übergeben:

+ +
/*\
+|*|
+|*|  Polyfill which enables the passage of arbitrary arguments to the
+|*|  callback functions of JavaScript timers (HTML5 standard syntax).
+|*|
+|*|  https://developer.mozilla.org/en-US/docs/DOM/window.setInterval
+|*|
+|*|  Syntax:
+|*|  var timeoutID = window.setTimeout(func, delay[, param1, param2, ...]);
+|*|  var timeoutID = window.setTimeout(code, delay);
+|*|  var intervalID = window.setInterval(func, delay[, param1, param2, ...]);
+|*|  var intervalID = window.setInterval(code, delay);
+|*|
+\*/
+
+(function() {
+  setTimeout(function(arg1) {
+    if (arg1 === 'test') {
+      // feature test is passed, no need for polyfill
+      return;
+    }
+    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);
+    };
+  }, 0, 'test');
+
+  var interval = setInterval(function(arg1) {
+    clearInterval(interval);
+    if (arg1 === 'test') {
+      // feature test is passed, no need for polyfill
+      return;
+    }
+    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);
+    };
+  }, 0, 'test');
+}())
+ +

Eine andere Möglichkeit ist, die Funktion innerhalb einer anonymen Funktion aufzurufen:

+ +
setTimeout(function() {
+    funktion("eins", "zwei", "drei");
+}, 1000);
+
+ +

Ebenfalls kann die Funktion bind() genutzt werden:

+ +

 

+ +
setTimeout(function(arg1, arg2, arg3){}.bind(undefined, "eins", "zwei", "drei"), 1000);
+ +

 

+ +

Das "this"-Problem

+ +

In der an setTimeout() übergebenen Funktion wird this bei Aufruf einen falschen Wert enthalten. Dieses Problem wird detailliert in der JavaScript-Referenz beschrieben.

+ +

Erklärung

+ +

Von setTimeout() ausgeführter Code wird in einem anderen Kontext ausgeführt, als in dem setTimeout() aufgerufen wurde. this wird deshalb in der aufgerufenen Funktion window oder global entsprechen, nicht dem this des Bereichs, in dem  setTimeout() aufgerufen wurde. Beispiel:

+ +
myArray = ["null", "eins", "drei"];
+myArray.myMethod = function (sProperty) {
+    alert(arguments.length > 0 ? this[sProperty] : this);
+};
+
+myArray.myMethod(); // Ausgabe: "null,eins,zwei"
+myArray.myMethod(1); // Ausgabe: "eins"
+setTimeout(myArray.myMethod, 1000); // Ausgabe: "[object Window]" nach 1 Sekunde
+setTimeout(myArray.myMethod, 1500, "1"); // Ausgabe: "undefined" nach 1,5 Sekunden
+// Versuchen wir, 'this' zu übergeben
+setTimeout.call(myArray, myArray.myMethod, 2000); // Fehler: "NS_ERROR_XPC_BAD_OP_ON_WN_PROTO: Illegal operation on WrappedNative prototype object"
+setTimeout.call(myArray, myArray.myMethod, 2500, 2); // Der gleiche Fehler
+ +

Es gibt hier keine Möglichkeit, this an die aufzurufende Funktion durchzureichen.

+ +

Eine Lösungsmöglichkeit

+ +

Eine Möglichkeit, das Problem zu umgehen, ist es, die beiden eingebauten Funktionen setTimeout() und setInterval() durch zwei eigene zu ersetzen, die sich Function.prototype.call bedienen:

+ +
// 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);
+};
+ +
Hinweis: Diese beiden Ersatzfunktionen ermöglichen es auch, im Internet Explorer Parameter an die aufzurufende Funktion zu übergeben, wie es HTML5 vorsieht. Sie können daher auch als {{anch("Polyfill")}} benutzt werden.
+ +

Anmerkungen

+ +

Eine Wartezeit kann mit window.clearTimeout() abgebrochen werden.

+ +

Soll eine Funktion wiederholt alle n Millisekunden aufgerufen werden, ist window.setInterval() die bessere Wahl.

+ +

Passing string literals

+ +

Passing a string instead of a function to setTimeout() suffers from the same hazards as using eval.

+ +
// Correct
+window.setTimeout(function() {
+    alert("Hello World!");
+}, 500);
+
+// Incorrect
+window.setTimeout("alert(\"Hello World!\");", 500);
+
+
+ +

String literals are evaluated in the global context, so local symbols in the context where setTimeout() was called will not be available when the string is evaluated as code.

+ +

Gründe für längere als gegebene Wartezeiten

+ +

Aus verschiedenen Gründen kann die tatsächliche Zeit bis zum Aufruf der Funktion länger sein als mit setTimeout() angegeben wurde. Dieser Abschnitt beschreibt die beiden häufigsten.

+ +

Wartezeiten betragen 4ms oder mehr

+ +

Um das System nicht zu überlasten, begrenzen moderne Browser die Häufigkeit der von setTimeout() und setInterval() ausgelösten Ereignisse ab einer bestimmten Aufruftiefe oder -häufigkeit. Beispiel:

+ +
function cb() { f(); setTimeout(cb, 0); }
+setTimeout(cb, 0);
+ +
setInterval(f, 0);
+ +

Chrome und Firefox drosseln nach dem fünften Aufruf, Safari nach dem sechsten, Edge bereits nach dem dritten.

+ +

Eine Wartezeit von 0 ms kann mit {{domxref("window.postMessage()")}} erreicht werden, wie hier beschrieben.

+ +

 

+ +
+

Hinweis: Die Mindestwartezeit, DOM_MIN_TIMEOUT_VALUE, beträgt 4 ms (Firefox-Einstellung dom.min_timeout_value), die Verschachtelungstiefe DOM_CLAMP_TIMEOUT_NESTING_LEVEL beträgt 5.

+
+ +
+

Hinweis: Der Wert 4 ms wurde mit HTML5 festgelegt und wird von allen Browsern umgesetzt, die nach 2010 erschienen sind. Vor {{geckoRelease("5.0")}} war der Mindestwert 10 ms.

+
+ +

 

+ +

 

+ +

Wartezeiten in inaktiven Tabs  größer als 1s

+ +

Um die Last noch weiter zu verringern, beträgt die Mindestwartezeit in sich im Hintergrund befindlichen Tabs grundsätzlich mindestens 1 s.

+ +

Firefox setzt diese Beschränkung seit Version 5 um (siehe {{bug(633421)}}). Der Wert von 1000 ms kann in der Einstellungen dom.min_background_timeout_value geändert werden.
+ Chrome setzt diese Beschränkung seit Version 11 um (crbug.com/66078).

+ +

Bei Firefox für Android beträgt seit Version 14 die Mindestwartezeit in sich im Hintergrund befindlichen Tabs 15 Minuten (siehe {{bug(736602)}}). Jegliche Aktivität in diesen Tabs kann auch vollständig angehalten werden.

+ +
+

Seit Version 50 gelten in Firefox keine Beschränkungen mehr, falls sich die Web Audio API {{domxref("AudioContext")}} im Wiedergabemodus befindet. Seit Firefox 51 gilt dies bereits für jegliche Dokumente mit einem {{domxref("AudioContext")}}, unabhängig von dessen Status.
+ Apps, die Musik Note für Note abspielen, konnten wegen der Beschränkungen den Takt nicht halten, sobald sie in den Hintergrund gelegt wurden.

+
+ +

Lastbedingte Verzögerungen

+ +

Zusätzlich zum aktiven Drosseln kann es zu verlängerten Wartezeiten kommen, falls das Dokument, der Browser oder das Betriebssystem anderweitig beschäftigt sind. Ein wichtiger Punkt in diesem Zusammenhang ist, dass die aufzurufende Funktion nicht ausgeführt werden kann, solange der Thread, der setTimeout() aufgerufen hat, noch aktiv ist:

+ +
function bla() {
+  console.log('bla wurde aufgerufen');
+}
+setTimeout(bla, 0);
+console.log('hinter setTimeout');
+ +

Ergebnis:

+ +
hinter setTimeout
+bla wurde aufgerufen
+ +

Obwohl setTimeout die sofortige Ausführung angewiesen wurde, wird der Aufruf von bla() in einer Warteschlange bis zur nächsten Gelegenheit zurückgestellt. Erst wenn der aktuell laufende Code ausgeführt wurde, werden die in der Warteschlange gesammelten Aufrufe abgearbeitet. In der Folge ist der Programmablauf nicht, wie eventuell erwartet.

+ +

Browserkompatibilität

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
EigenschaftChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basis1.0{{ CompatGeckoDesktop("1") }}4.04.01.0
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
EigenschaftAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic1.01.0{{ CompatGeckoMobile("1") }}6.06.01.0
+
+ +

Spezifikation

+ +

Gehört zu DOM-Level 0, wie spezifiziert in HTML5.

+ +

Siehe auch

+ + diff --git a/files/de/web/api/worker/index.html b/files/de/web/api/worker/index.html new file mode 100644 index 0000000000..258fc77862 --- /dev/null +++ b/files/de/web/api/worker/index.html @@ -0,0 +1,191 @@ +--- +title: Worker +slug: Web/API/Worker +translation_of: Web/API/Worker +--- +

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

+ +

Das Worker Interface der Web Workers API beschreibt eine im Hintergrund ausgeführte Programmlogik, die leicht erstellt werden kann und Nachrichten mit dem Ersteller austauschen. Einen Worker erzeugen erfolgt einfach über den Aufruf des Worker() Konstruktors unter Angabe eines Scripts, welches in dem Worker Thread ausgeführt werden soll.

+ +

Worker selbst können zudem weitere (sog. "verschachtelte") Worker erzeugen, solange diese in demselben origin wie die übergeordnete Seite liegen (Achtung: verschachtelte Worker sind aktuell nicht in Blink implementiert).  Zusätzlich können Worker das XMLHttpRequest nutzen, um auf Netzwerk I/O zuzugreifen, unter der Voraussetzung, dass die Attribute responseXML und channel des XMLHttpRequest immer den Wert null zurück liefern.

+ +

Nicht alle Interfaces und Funktionen sind verfügbar für das mit dem Worker assoziierte Script.

+ +

Zur Verwendung eines Workers mit Zugriff auf js-ctypes in Browser-Erweiterungen (Extension) für den Firefox bitte das {{ domxref("ChromeWorker") }} Objekt nutzen.

+ +

Constructors

+ +
+
{{domxref("Worker.Worker", "Worker()")}}
+
Erzeugt einen neuen Web Worker, der das über seine URL referenzierte Script ausführt. Worker können auch über Blobs erzeugt werden.
+
+ +

Properties

+ +

Erbt die Eigenschaften seines parents, {{domxref("EventTarget")}}, und implementiert die Eigenschaften von {{domxref("AbstractWorker")}}.

+ +

Event handlers

+ +
+
{{domxref("AbstractWorker.onerror")}}
+
Ein {{ domxref("EventListener") }}, welcher jedesmal dann aufgerufen wird, wenn ein {{domxref("ErrorEvent")}} des Typs error den Worker erreicht. Dies ist geerbt von {{domxref("AbstractWorker")}}.
+
{{domxref("Worker.onmessage")}}
+
Ein {{ domxref("EventListener") }}, welcher jedesmal dann aufgerufen wird, wenn ein {{domxref("MessageEvent")}} des Typs message den Worker erreicht — d.h. der Worker erhält eine Nachricht von seinem übergeordneten document via {{domxref("DedicatedWorkerGlobalScope.postMessage")}}. Diese Nachricht wird innerhalb des Events in der {{domxref("MessageEvent.data", "data")}} Eigenschaft gespeichert.
+
{{domxref("Worker.onmessageerror")}}
+
Der {{domxref("EventHandler")}}, dessen Code aufgerufen werden soll, wenn es zu einem {{event("messageerror")}} Event kommt.
+
+ +
+
+ +

Methods

+ +

Erbt die Methoden seines parents, {{domxref("EventTarget")}}, und implementiert die Methoden von {{domxref("AbstractWorker")}}.

+ +
+
{{domxref("Worker.postMessage()")}}
+
Sendet eine Nachricht an den Worker. Diese kann dabei aus einem beliebigen JavaScript Objekt bestehen.
+
{{domxref("Worker.terminate()")}}
+
Beendet den Worker unmittelbar. Hierüber besteht dabei nicht die Möglichkeit, dem Worker die Gelegenheit für ein geordnetes Beenden von laufenden Operationen zu geben. Vielmehr wird der Worker sofort beendet. ServiceWorker Instanzen unterstützen diese Methode nicht.
+
+ +

Example

+ +

Das nachfolgende Beispiel zeigt wie ein {{domxref("Worker")}} mittels des {{domxref("Worker.Worker", "Worker()")}} Konstruktors erzeugt und verwendet wird:

+ +
var myWorker = new Worker('worker.js');
+var first = document.querySelector('#number1');
+var second = document.querySelector('#number2');
+
+first.onchange = function() {
+  myWorker.postMessage([first.value,second.value]);
+  console.log('Message posted to worker');
+}
+ +

Ein vollständiges Beispiel findet sich hier: Basic dedicated worker example (run dedicated worker).

+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "#worker", "Worker")}}{{Spec2('HTML WHATWG')}} 
+ +

Browser compatibility

+ +

Die Unterstützung der einzelnen Worker ist abhängig vom Typ und variiert. Wie ein Worker konkret unterstützt wird, kann der Seite zu dem Worker Typ entnommen werden.

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support4{{CompatVersionUnknown}}3.510.010.64
Constructor name option{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatGeckoDesktop(55)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
onmessageerror60{{CompatUnknown}}{{CompatGeckoDesktop(57)}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)IE PhoneOpera MobileSafari MobileChrome for Android
Basic support4.4{{CompatVersionUnknown}}3.510.011.55.1{{CompatUnknown}}
Constructor name option{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile(55)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}
onmessageerror60{{CompatUnknown}}{{CompatGeckoMobile(57)}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

Cross-origin worker error behaviour

+ +

In früheren Browserversionen kam es zu einem SecurityError bei dem Versuch ein Script für einen cross-origin worker zu laden. In neueren Browsern wird, aufgrund einer Änderung der Spezifikation, stattdessen ein {{event("error")}} Event erzeugt. Mehr über den Umgang mit solchen Fehlern ist hier zu finden: Loading cross-origin worker now fires error event instead of throwing; worker in sandboxed iframe no longer allowed.

+ +

See also

+ + diff --git a/files/de/web/api/xmlhttprequest/index.html b/files/de/web/api/xmlhttprequest/index.html new file mode 100644 index 0000000000..913acfb17a --- /dev/null +++ b/files/de/web/api/xmlhttprequest/index.html @@ -0,0 +1,710 @@ +--- +title: XMLHttpRequest +slug: Web/API/XMLHttpRequest +translation_of: Web/API/XMLHttpRequest +--- +

{{APIRef("XMLHttpRequest")}}

+ +

XMLHttpRequest ist ein JavaScript Objekt, das von Microsoft entwickelt und von Mozilla, Apple, und Google übernommen wurde. Es wird derzeit im W3C standardisiert. Es bietet einen einfachen Weg, Daten von einem URL zu erhalten. Trotz seines Namens kann man mit XMLHttpRequest jede Art von Daten laden, nicht nur XML, und es unterstützt auch andere Protokolle als HTTP (inklusive file und ftp).

+ +

Eine Instanz von XMLHttpRequest erzeugt man ganz einfach so:

+ +
var myRequest = new XMLHttpRequest();
+
+ +

Für Näheres zur Verwendung von XMLHttpRequest, siehe Using XMLHttpRequest.

+ +

Übersicht: Methoden

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
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);
Nicht-Standard Methoden
[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);
+ +

Eigenschaften

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
AttributTypBeschreibung
+

onreadystatechange

+
Function? +

Ein JavaScript function Objekt, das bei jedem Wechsel des readyState Attributs aufgerufen wird. Das Callback wird aus dem Thread der Benutzerschnittstelle aufgerufen.

+ +
Warnung: Dies sollte nicht mit synchronen Anfragen und darf nicht aus nativem Code heraus verwendet werden.
+
readyStateunsigned short +

Der Status der Anfrage:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
WertStatusBeschreibung
0UNSENTopen()wurde noch nicht aufgerufen.
1OPENEDsend()wurde noch nicht aufgerufen.
2HEADERS_RECEIVEDsend() wurde aufgerufen, und Headers sowie Status sind verfügbar.
3LOADINGDownload ist im Gange; responseText enthält bereits unvollständige Daten.
4DONEDer Vorgang ist abgeschlossen.
+
responsevariiert +

Der Entitätskörper der Antwort (response entity body) gemäss responseType, als ein ArrayBuffer, Blob, {{domxref("Document")}}, JavaScript Objekt (für "json"), oder string. Dies ist null falls die Anfrage nicht abgeschlossen ist oder erfolglos war.

+
responseText {{ReadOnlyInline}}DOMStringDie Antwort auf die Anfrage als Text, oder null falls die Anfrage nicht abgeschlossen ist oder erfolglos war.
responseTypeXMLHttpRequestResponseType +

Kann gesetzt werden, um den Datentyp der Antwort zu ändern.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
WertDatentyp der response Eigenschaft
"" (leerer String)String (Das ist der Default)
"arraybuffer"ArrayBuffer
"blob"{{domxref("Blob")}}
"document"{{domxref("Document")}}
"json"JavaScript Objekt, geparsed aus einem JSON String, der vom Server zurückgegeben wird.
"text"String
"moz-blob"Wird von Firefox verwendet, um den Bezug partieller {{domxref("Blob")}} Daten von progress Events zu erlauben. Dadurch kann ein progress Event Handler bereits mit der Verarbeitung von Daten beginnen, während ihr Empfang noch läuft.
"moz-chunked-text" +

Ähnlich wie "text", aber streamt die Daten. Das bedeutet, dass der Wert in response nur während des "progress" Event verfügbar ist und jeweils nur die Daten enthält, die seit dem letzten "progress" Event eingetroffen sind.

+ +

Wenn auf response während eines "progress" Events zugegriffen wird, enthält es einen String mit den Daten. Andernfalls gibt es null zurück.

+ +

Dieser Modus funktioniert derzeit nur in Firefox.

+
"moz-chunked-arraybuffer" +

Ähnlich wie "arraybuffer", aber streamt die Daten. Das bedeutet, dass der Wert in response nur während des "progress" Event verfügbar ist und jeweils nur die Daten enthält, die seit dem letzten "progress" Event eingetroffen sind.

+ +

Wenn auf response während eines "progress" Events zugegriffen wird, enthält es einen ArrayBuffer mit den Daten. Andernfalls gibt es null zurück.

+ +

Dieser Modus funktioniert derzeit nur in Firefox.

+
+ +
Anmerkung: Ab Gecko 11.0  sowie WebKit build 528 kann man in diesen Browsern das responseType Attribut nicht mehr für synchrone Anfragen benutzen. Der Versuch löst einen NS_ERROR_DOM_INVALID_ACCESS_ERR Fehler aus. Diese Änderung wurde dem W3C zur Standardisierung vorgeschlagen.
+
responseXML {{ReadOnlyInline}}Document? +

Die Antwort auf die Anfrage als DOM Document Objekt, oder null falls die Anfrage erfolglos war, noch nicht gesendet wurde, oder nicht als XML oder HTML geparst werden kann. Die Antwort wird geparst, als wäre sie ein text/xml Stream. Wenn der responseType auf "document" gesetzt wurde und die Anfrage asynchron gemacht wurde, wird die Antwort geparst, als wäre sie ein text/html Stream.

+ +
Anmerkung: Falls der Server nicht den text/xml Inhaltstyp-Header auf die Antwort anwendet, kann man overrideMimeType() verwenden, um XMLHttpRequest zu zwingen, sie dennoch als XML zu parsen.
+
status {{ReadOnlyInline}}unsigned shortDer Status der Antwort auf die Anfrage. Das ist der HTTP Ergebnis-Code (status ist z.B. 200 für eine erfolgreiche Anfrage).
statusText {{ReadOnlyInline}}DOMStringDer Antwort-String, der vom HTTP Server zurückgesendet wurde. Im Gegensatz zu status beinhaltet dies den ganzen Text der Antwortnachricht (z.B. "200 OK").
timeoutunsigned long +

Die Anzahl Millisekunden, die eine Anfrage dauern darf, bevor sie automatisch abgebrochen wird. Ein Wert von 0 (das ist die Voreinstellung) bedeutet, dass es kein timeout gibt.

+ +
Anmerkung: Für synchrone Anfragen mit einem besitzenden Fenster darf man kein timeout verwenden.
+
uploadXMLHttpRequestUploadDas Hochladen kann mitverfolgt werden, indem man einen Event Listener zu upload hinzufügt.
withCredentialsboolean +

Zeigt an, ob Site-übergreifende Access-Control Anfragen mit Credentials wie Cookies oder Autorisierungs-Headers durchgeführt werden sollen oder nicht. Die Voreinstellung ist false.

+ +
Anmerkung: Anfragen an die ursprüngliche Site sind davon niemals betroffen.
+ +
Anmerkung: Ab Gecko 11.0 kann man das withCredentials Attribut nicht mehr für synchrone Anfragen verwenden. Der Versuch löst einen NS_ERROR_DOM_INVALID_ACCESS_ERR Fehler aus.
+
+ +

Nicht-Standard Eigenschaften

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
AttributTypDescription
channel {{ReadOnlyInline}}{{Interface("nsIChannel")}}Der Kanal, der vom Objekt zur Durchführung der Anfrage verwendet wurde. Das ist null falls der Kanal noch nicht erzeugt worden ist. Im Falle von mehrteiligen Anfragen ist das der anfängliche Kanal, nicht derjenige der anderen Teile der mehrteiligen Anfrage.
+ Zugriff nur mit erhöhten Rechten.
mozAnon {{ReadOnlyInline}}boolean +

Falls true wird die Anfrage ohne Cookie und Authentisierungs-Headers gesendet.

+
mozSystem {{ReadOnlyInline}}boolean +

Falls true wird die Regel, die nur Anfragen zum gleichen Ursprung erlaubt, für diese Anfrage nicht durchgesetzt.

+
mozBackgroundRequestboolean +

Zeigt an, ob das Objekt eine Service-Anfrage im Hintergrund darstellt. Falls true wird keine Lastgruppe mit der Anfrage verknüpft, und die Anzeige von Sicherheits-Dialogen wird verhindert. Zugriff nur mit erhöhten Rechten.

+ +

In Fällen, wo normalerweise ein Sicherheits-Dialog angezeigt würde (wie Autorisierungs- oder Zertifikatsfehler-Benachrichtigungen), schlägt die Anfrage stattdessen einfach fehl.

+ +
Anmerkung: Diese Eigenschaft muss vor dem Aufrufen von open() gesetzt werden..
+
mozResponseArrayBuffer  {{obsolete_inline("6")}} {{ReadOnlyInline}}ArrayBufferDie Antwort auf die Anfrage, als typisiertes JavaScript Array. Dies ist NULL falls die Anfrage erfolglos war oder noch nicht gesendet wurde.
multipart {{obsolete_inline("22")}}boolean +

Dieses nur in Gecko verfügbare Feature wurde in Firefox/Gecko 22 entfernt. Bitte verwende stattdessen Server-Sent Events, Web Sockets oder responseText aus progress Events.

+ +

Zeigt an, ob als Antwort ein Stream von möglicherweise mehreren XML Dokumenten erwartet wird. Wird dies auf true gesetzt, muss der Inhaltstyp des ersten Teils der Antwort multipart/x-mixed-replace sein, sonst tritt ein Fehler auf. Alle Anfragen müssen asynchron sein.

+ +

Dies ermöglicht die Unterstützung von Server Push; für jedes XML Dokument, das in die Antwort auf diese Anfrage geschrieben wird, wird ein neues XML DOM Dokument erzeugt, und zwischen den Dokumenten wird der onload Handler aufgerufen.

+ +
Anmerkung: Wenn dies gesetzt ist, werden onload und andere Event Handler nicht zurückgesetzt, nachdem das erste XML Dokument geladen ist, und der onload Handler wird nach Erhalt jedes Teils der Antwort aufgerufen.
+
+ +

Konstruktor

+ +

XMLHttpRequest()

+ +

Der Konstruktor initiiert ein XMLHttpRequest Objekt. Er muss vor allen anderen Methoden aufgerufen werden.

+ +

Gecko/Firefox 16 fügt einen nicht-standard Parameter zum Konstruktor hinzu, der den anonymen Modus einschalten kann (siehe Bug 692677). Das mozAnon flag auf true zu setzen, hat einen ähnlichen Effekt wie der AnonXMLHttpRequest() Konstruktor, der in der XMLHttpRequest Spezifikation beschrieben ist, aber noch in keinem Browser implementiert wurde (Stand September 2012).

+ +
XMLHttpRequest (
+  JSObject objParameters
+);
+ +
Parameter (nicht-standard)
+ +
+
objParameters
+
Es gibt zwei Flags, die gesetzt werden können: +
+
mozAnon
+
Boolean: Wenn dieses Flag auf true gesetzt ist, wird der Browser weder den Ursprung der Anfrage noch Anmeldedaten übermitteln, wenn er Daten anfordert. Das heisst vor allem auch, dass keine Cookies gesendet werden, sofern sie nicht ausdrücklich mit setRequestHeader hinzugefügt wurden.
+
mozSystem
+
Boolean: Dieses Flag auf true zu setzen, ermöglicht das Herstellen von Cross-Site Verbindungen, ohne dass der Server dem mittels CORS zustimmen muss. Erfodert das Setzen von mozAnon: true. D.h. das kann nicht mit dem Senden von Cookies oder anderen Anmeldeinformationen kombiniert werden. Dies funktioniert nur in privilegierten (reviewed) Apps; es klappt nicht auf beliebigen Webseiten, die in Firefox geladen werden.
+
+
+
+ +

Methoden

+ +

abort()

+ +

Bricht die Anfrage ab, falls sie bereits gesendet wurde.

+ +

getAllResponseHeaders()

+ +
DOMString getAllResponseHeaders();
+ +

Liefert alle Antwort-Header als String, oder null falls keine Antwort empfangen wurde.

+ +

Anmerkung: Für mehrteilige Anfragen gibt dies die Header des aktuellen Teils der Anfrage zurück, nicht die des ursprünglichen Kanals.

+ +

getResponseHeader()

+ +
DOMString? getResponseHeader(DOMString header);
+ +

Liefert den String mit dem Text des angegebenen Headers, oder null falls die Antwort noch nicht empfangen wurde oder der Header in der Antwort nicht existiert.

+ +

open()

+ +

Initialisiert eine Anfrage. Diese Methode ist nur zur Verwendung in JavaScript Code; um eine Anfrage aus nativem Code zu initialisieren, ist stattdessen openRequest() zu benutzen.

+ +
Anmerkung: Der Aufruf dieser Methode für eine bereits aktive Anfrage (eine, für die open()oder openRequest() schon ausgeführt wurde) ist gleichwertig mit  dem Aufruf von abort().
+ +
void open(
+   DOMString method,
+   DOMString url,
+   optional boolean async,
+   optional DOMString user,
+   optional DOMString password
+);
+
+ +
Parameter
+ +
+
method
+
Die zu benutzende HTTP Methode,  wie "GET", "POST", "PUT", "DELETE", etc. Wird für nicht-HTTP(S) URLs ignoriert.
+
url
+
Der URL, an den die Anfrage geschickt werden soll.
+
async
+
Ein optionaler boole'scher Parameter mit Defaultwert true, der angibt, ob die Operation asynchron ausgeführt werden soll. Wenn dieser Wert false ist, kehrt die send()Methode nicht zurück, bis die Antwort vollständig empfangen worden ist. Ist er true, kehrt sie sofort zurück, und die Benachrichtigung über die vollendete Transaktion erfolgt mittels Events. Dies muss true sein falls das multipart Attribut true ist, sonst wird ein Fehler ausgelöst.
+
user
+
Der optionale Benutzername zum Zweck der Authentisierung; ohne Angabe ist dies ein leerer String.
+
password
+
Das optionale Passwort zum Zweck der Authentisierung; ohne Angabe ist dies ein leerer String.
+
+ +

overrideMimeType()

+ +

Übergeht den vom Server zurückgegebenen MIME Typ. Dies kann beispielsweise benutzt werden, um zu erzwingen, dass ein Stream als text/xml behandelt und geparst wird, selbst wenn ihn der Server nicht als das meldet. Diese Methode muss vor send() aufgerufen werden.

+ +
void overrideMimeType(DOMString mimetype);
+ +

send()

+ +

Sendet die Anfrage. Falls die Anfage asynchron ist (was der Default ist), kehrt diese Methode zurück, sobald die Anfrage gesendet ist. Ist die Anfrage synchron, kehrt diese Methode nicht zurück, bis die Antwort angekommen (oder ein Timeout aufgetreten) ist.

+ +
Anmerkung: Jegliche zu setzende Event Handler / Listener müssen vor dem Aufruf von send() gesetzt werden.
+ +
void send();
+void send(ArrayBuffer data);
+void send(Blob data);
+void send(Document data);
+void send(DOMString? data);
+void send(FormData data);
+ +
Anmerkungen
+ +

Falls data ein Document ist, so wird dieses vor dem Senden serialisiert. Beim Senden eines Document senden Firefox Versionen vor Version 3 die Anfrage immer encodiert als UTF-8; Firefox 3 sendet das Document richtigerweise mit dem angegebenen body.xmlEncoding, oder UTF-8 falls keines angegeben wurde.

+ +

Falls es ein nsIInputStream ist, muss er kompatibel sein mit der setUploadStream()Methode des nsIUploadChannel. In diesem Fall wird die Länge des Inhalts in einem Content-Length Header zur Anfrage hinzugefügt, dessen Wert mit der available()Methode des nsIInputStream ermittelt wird. Jegliche Header, die am Anfang des Streams enthalten sind, werden als Teil des Nachrichtenkörpers behandelt. Der MIME Typ des Streams sollte vor dem Aufruf von send() angegeben werden, indem der Content-Type Header mit der  setRequestHeader() Methode gesetzt wird.

+ +

Der beste Weg, um binäre Inhalte zu senden (wie beim Hochladen einer Datei), ist die Verwendung von ArrayBuffern oder Blobs in Verbindung mit der send() Methode. Wenn jedoch stringifizierbare Rohdaten gesendet werden sollen, ist die sendAsBinary() Methode zu verwenden.

+ +

setRequestHeader()

+ +

Setzt den Wert eines HTTP Anfrage-Headers. Aufrufe von setRequestHeader() müssen nach open(), aber vor send() erfolgen.

+ +
void setRequestHeader(
+   DOMString header,
+   DOMString value
+);
+
+ +
Parameter
+ +
+
header
+
Der Name des zu setzenden Headers.
+
value
+
Der Wert des zu setzenden Headers.
+
+ +

Nicht-Standard Methoden

+ +

init()

+ +

Initialisiert das Objekt für die Verwendung aus C++ Code.

+ +
Warnung: Diese Methode darf nicht aus JavaScript heraus aufgerufen werden.
+ +
[noscript] void init(
+   in nsIPrincipal principal,
+   in nsIScriptContext scriptContext,
+   in nsPIDOMWindow ownerWindow
+);
+
+ +
Parameter
+ +
+
principal
+
Das Prinzipal, das für die Anfrage benutzt werden soll; darf nicht null sein.
+
scriptContext
+
Der Skript-Kontext, der für die Anfrage benutzt werden soll; darf nicht null sein.
+
ownerWindow
+
Das Fenster, das zu der Anfrage gehört; darf null sein.
+
+ +

openRequest()

+ +

Initialisiert eine Anfrage. Diese Methode ist zur Verwendung in nativem Code; um eine Anfrage in JavaScript Code zu initialisieren, ist stattdessen open() zu verwenden. Siehe Dokumentation für open().

+ +

sendAsBinary()

+ +

Eine Variante der send() Methode, die binäre Daten schickt.

+ +
void sendAsBinary(
+   in DOMString body
+);
+
+ +

Diese Methode, zusammen mit der readAsBinaryString Methode der FileReader API, ermöglichen das Lesen und den Upload jeglicher Dateitypen und das Stringifizieren der Rohdaten.

+ +
Parameter
+ +
+
body
+
Der Körper der Anfrage als DOMstring. Diese Daten werden durch Beschneiden (Entfernen des höherwertigen Bytes jedes Zeichens) in Einzel-Byte-Zeichen umgewandelt.
+
+ +
sendAsBinary() polyfill
+ +

Da sendAsBinary() ein experimentelles Feature ist, kommt hier ein Polyfill für Browser, die sendAsBinary() nicht unterstützen, dafür aber typisierte Arrays.

+ +
/*\
+|*|
+|*|  :: XMLHttpRequest.prototype.sendAsBinary() Polyfill ::
+|*|
+|*|  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;
+    }
+    /* sende als ArrayBufferView...: */
+    this.send(ui8Data);
+    /* ...oder als ArrayBuffer (altmodisch)...: this.send(ui8Data.buffer); */
+  };
+}
+ +
Anmerkung: Dieses Polyfill kann mit zwei Datentypen als Argument für send() gebaut werden: einem ArrayBuffer (ui8Data.buffer – kommentierter Code) oder einer ArrayBufferView (ui8Data, das ist ein typisiertes Array von 8-bit Ganzzahlen ohne Vorzeichen – unkommentierter Code). Wenn man jedoch in Google Chrome versucht, einen ArrayBuffer zu senden, erscheint die folgende Warnmeldung: ArrayBuffer is deprecated in XMLHttpRequest.send(). Use ArrayBufferView instead.
+ +

Anmerkungen

+ + + +

Events

+ +

onreadystatechange als eine Eigenschaft der XMLHttpRequest Instanz wird von allen Browsern unterstützt.

+ +

Seither wurden einige zusätzliche Event Handler in verschiedenen Browsern implementiert (onload, onerror, onprogress, etc.). Diese werden in Firefox unterstützt. Für Genaueres, siehe {{interface("nsIXMLHttpRequestEventTarget")}} und Using XMLHttpRequest.

+ +

Neuere Browser, inklusive Firefox, unterstützen das 'Horchen' nach XMLHttpRequest Ereignissen mittels der Standard addEventListener APIs zusätzlich zum Setzen von on* Eigenschaften auf eine Handler Funktion.

+ +

Browser Kompatibilität

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Grundsätzliche Unterstützung (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}} – benutze 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 für AndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Grundsätzliche Unterstützung{{CompatUnknown}}0.16{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

Gecko Anmerkungen

+ +

Gecko 11.0 {{geckoRelease("11.0")}} entfernte die Unterstützung für die Verwendung der responseType und withCredentials Attribute bei der Durchführung synchroner Anfragen. Der Versuch löst einen NS_ERROR_DOM_INVALID_ACCESS_ERR Fehler aus. Diese Änderung wurde dem W3C zur Standardisierung vorgeschlagen.

+ +

Gecko 12.0 {{geckoRelease("12.0")}} und spätere unterstützen die Verwendung von XMLHttpRequest zum Lesen von data: URLs.

+ +

Siehe auch

+ + diff --git a/files/de/web/api/xmlhttprequest/using_xmlhttprequest/index.html b/files/de/web/api/xmlhttprequest/using_xmlhttprequest/index.html new file mode 100644 index 0000000000..f15901a388 --- /dev/null +++ b/files/de/web/api/xmlhttprequest/using_xmlhttprequest/index.html @@ -0,0 +1,789 @@ +--- +title: Using XMLHttpRequest +slug: Web/API/XMLHttpRequest/Using_XMLHttpRequest +translation_of: Web/API/XMLHttpRequest/Using_XMLHttpRequest +--- +
{{APIRef ("XMLHttpRequest")}}
+ +

In diesem Handbuch wird erläutert, wie Sie mit {{domxref ("XMLHttpRequest")}} HTTP- Anforderungen ausgeben , um Daten zwischen der Website und einem Server auszutauschen . Beispiele für häufig vorkommende und unklarere Anwendungsfälle XMLHttpRequestsind enthalten.

+ +

Um eine HTTP-Anfrage zu senden, erstellen Sie ein XMLHttpRequestObjekt, öffnen Sie eine URL und senden Sie die Anfrage. Nach Abschluss der Transaktion enthält das Objekt nützliche Informationen wie den Antworttext und den HTTP-Status des Ergebnisses.

+ +
function reqListener () {
+  console.log(this.responseText);
+}
+
+var oReq = new XMLHttpRequest();
+oReq.addEventListener("load", reqListener);
+oReq.open("GET", "http://www.example.org/example.txt");
+oReq.send();
+ +

Arten von Anfragen

+ +
+

Eine Anforderung über XMLHttpRequestkann die Daten auf zwei Arten asynchron oder synchron abrufen. Die Art der Anforderung wird durch das optionale asyncArgument (das dritte Argument) bestimmt, das für die Methode {{domxref ("XMLHttpRequest.open ()")}} festgelegt wird. Wenn dieses Argument angegeben ist trueoder nicht, XMLHttpRequestwird das asynchron verarbeitet, andernfalls wird der Prozess synchron behandelt. Eine ausführliche Diskussion und Demonstration dieser beiden Arten von Anforderungen finden Sie auf der Seite für synchrone und asynchrone Anforderungen . Verwenden Sie keine synchronen Anforderungen außerhalb von Web Workers.

+
+ +
Hinweis: Ab Gecko 30.0 {{geckoRelease ("30.0")}} sind synchrone Anforderungen im Hauptthread aufgrund der negativen Auswirkungen auf die Benutzererfahrung veraltet.
+ +
Hinweis: Die Konstruktorfunktion XMLHttpRequestist nicht nur auf XML-Dokumente beschränkt. Es beginnt mit "XML", da das Hauptformat, das ursprünglich für den asynchronen Datenaustausch verwendet wurde, bei der Erstellung XML war
+ +

Umgang mit Antworten

+ +

Es gibt verschiedene Arten von Antwortattributen, die durch die Living Standard-Spezifikation für den Konstruktor {{domxref ("XMLHttpRequest.XMLHttpRequest", "XMLHttpRequest ()")}} definiert sind. Diese teilen dem Kunden die XMLHttpRequestwichtigen Informationen über den Status der Antwort mit. In den folgenden Abschnitten werden einige Fälle beschrieben, in denen der Umgang mit Nicht-Text-Antworttypen möglicherweise manipuliert und analysiert wird.

+ +

Analysieren und Bearbeiten der responseXML-Eigenschaft

+ +

If you use XMLHttpRequest to get the content of a remote XML document, the {{domxref("XMLHttpRequest.responseXML", "responseXML")}} property will be a DOM object containing a parsed XML document. This could prove difficult to manipulate and analyze. There are four primary ways of analyzing this XML document:

+ +
    +
  1. Using XPath to address (or point to) parts of it.
  2. +
  3. Manually Parsing and serializing XML to strings or objects.
  4. +
  5. Using {{domxref("XMLSerializer")}} to serialize DOM trees to strings or to files.
  6. +
  7. {{jsxref("RegExp")}} can be used if you always know the content of the XML document beforehand. You might want to remove line breaks, if you use RegExp to scan with regard to line breaks. However, this method is a "last resort" since if the XML code changes slightly, the method will likely fail.
  8. +
+ +
+

Note: XMLHttpRequest can now interpret HTML for you using the {{domxref("XMLHttpRequest.responseXML", "responseXML")}} property. Read the article about HTML in XMLHttpRequest to learn how to do this.

+
+ +

Processing a responseText property containing an HTML document

+ +

If you use XMLHttpRequest to get the content of a remote HTML webpage, the {{domxref("XMLHttpRequest.responseText", "responseText")}} property is a string containing the raw HTML. This could prove difficult to manipulate and analyze. There are three primary ways to analyze and parse this raw HTML string:

+ +
    +
  1. Use the XMLHttpRequest.responseXML property as covered in the article HTML in XMLHttpRequest.
  2. +
  3. Inject the content into the body of a document fragment via fragment.body.innerHTML and traverse the DOM of the fragment.
  4. +
  5. {{jsxref("RegExp")}} can be used if you always know the content of the HTML responseText beforehand. You might want to remove line breaks, if you use RegExp to scan with regard to linebreaks. However, this method is a "last resort" since if the HTML code changes slightly, the method will likely fail.
  6. +
+ +

Handling binary data

+ +

Although {{domxref("XMLHttpRequest")}} is most commonly used to send and receive textual data, it can be used to send and receive binary content. There are several well tested methods for coercing the response of an XMLHttpRequest into sending binary data. These involve utilizing the {{domxref("XMLHttpRequest.overrideMimeType", "overrideMimeType()")}} method on the XMLHttpRequest object and is a workable solution.

+ +
var oReq = new XMLHttpRequest();
+oReq.open("GET", url);
+// retrieve data unprocessed as a binary string
+oReq.overrideMimeType("text/plain; charset=x-user-defined");
+/* ... */
+
+ +

However, more modern techniques are available, since the {{domxref("XMLHttpRequest.responseType", "responseType")}} attribute now supports a number of additional content types, which makes sending and receiving binary data much easier.

+ +

For example, consider this snippet, which uses the responseType of "arraybuffer" to fetch the remote content into a {{jsxref("ArrayBuffer")}} object, which stores the raw binary data.

+ +
var oReq = new XMLHttpRequest();
+
+oReq.onload = function(e) {
+  var arraybuffer = oReq.response; // not responseText
+  /* ... */
+}
+oReq.open("GET", url);
+oReq.responseType = "arraybuffer";
+oReq.send();
+ +

For more examples check out the Sending and Receiving Binary Data page

+ +

Monitoring progress

+ +

XMLHttpRequest provides the ability to listen to various events that can occur while the request is being processed. This includes periodic progress notifications, error notifications, and so forth.

+ +

Support for DOM {{event("progress")}} event monitoring of XMLHttpRequest transfers follows the specification for progress events: these events implement the {{domxref("ProgressEvent")}} interface. The actual events you can monitor to determine the state of an ongoing transfer are:

+ +
+
{{event("progress")}}
+
The amount of data that has been retrieved has changed.
+
{{event("load")}}
+
The transfer is complete; all data is now in the response
+
+ +
var oReq = new XMLHttpRequest();
+
+oReq.addEventListener("progress", updateProgress);
+oReq.addEventListener("load", transferComplete);
+oReq.addEventListener("error", transferFailed);
+oReq.addEventListener("abort", transferCanceled);
+
+oReq.open();
+
+// ...
+
+// progress on transfers from the server to the client (downloads)
+function updateProgress (oEvent) {
+  if (oEvent.lengthComputable) {
+    var percentComplete = oEvent.loaded / oEvent.total * 100;
+    // ...
+  } else {
+    // Unable to compute progress information since the total size is unknown
+  }
+}
+
+function transferComplete(evt) {
+  console.log("The transfer is complete.");
+}
+
+function transferFailed(evt) {
+  console.log("An error occurred while transferring the file.");
+}
+
+function transferCanceled(evt) {
+  console.log("The transfer has been canceled by the user.");
+}
+ +

Lines 3-6 add event listeners for the various events that are sent while performing a data transfer using XMLHttpRequest.

+ +
Note: You need to add the event listeners before calling open() on the request. Otherwise the progress events will not fire.
+ +

The progress event handler, specified by the updateProgress() function in this example, receives the total number of bytes to transfer as well as the number of bytes transferred so far in the event's total and loaded fields. However, if the lengthComputable field is false, the total length is not known and will be zero.

+ +

Progress events exist for both download and upload transfers. 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);
+oReq.upload.addEventListener("load", transferComplete);
+oReq.upload.addEventListener("error", transferFailed);
+oReq.upload.addEventListener("abort", transferCanceled);
+
+oReq.open();
+
+ +
Note: Progress events are not available for the file: protocol.
+ +
+

Note: Starting in {{Gecko("9.0")}}, progress events can now be relied upon to come in for every chunk of data received, including the last chunk in cases in which the last packet is received and the connection closed before the progress event is fired. In this case, the progress event is automatically fired when the load event occurs for that packet. This lets you now reliably monitor progress by only watching the "progress" event.

+
+ +
+

Note: As of {{Gecko("12.0")}}, if your progress event is called with a responseType of "moz-blob", the value of response is a {{domxref("Blob")}} containing the data received so far.

+
+ +

One can also detect all three load-ending conditions (abort, load, or error) using the loadend event:

+ +
req.addEventListener("loadend", loadEnd);
+
+function loadEnd(e) {
+  console.log("The transfer finished (although we don't know if it succeeded or not).");
+}
+
+ +

Note there is no way to be certain, from the information received by the loadend event, as to which condition caused the operation to terminate; however, you can use this to handle tasks that need to be performed in all end-of-transfer scenarios.

+ +

Submitting forms and uploading files

+ +

Instances of XMLHttpRequest can be used to submit forms in two ways:

+ + + +

Using the FormData API is the simplest and fastest, but has the disadvantage that data collected can not be stringified.
+ Using only AJAX is more complex, but typically more flexible and powerful.

+ +

Using nothing but XMLHttpRequest

+ +

Submitting forms without the FormData API does not require other APIs for most use cases. The only case where you need an additional API is if you want to upload one or more files, where you use the {{domxref("FileReader")}} API.

+ +

A brief introduction to the submit methods

+ +

An html {{ HTMLElement("form") }} can be sent in four ways:

+ + + +

Now, consider the submission of 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 examples, depending on the encoding type you are using:

+ + + +

However, 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 effects are done automatically by the web browser whenever you submit a {{HTMLElement("form")}}. If you want to perform the same effects using JavaScript you have to instruct the interpreter about everything. Therefore, how to send forms in pure AJAX is too complex to be explained here in detail. For this reason, here we place a complete (yet didactic) framework, able to use all four ways to submit, and 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() Polyfill ::
+|*|
+|*|  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.
+|*|  https://www.gnu.org/licenses/gpl-3.0-standalone.html
+|*|
+|*|  Syntax:
+|*|
+|*|   AJAXSubmit(HTMLFormElement);
+\*/
+
+var AJAXSubmit = (function () {
+
+  function ajaxSuccess () {
+    /* console.log("AJAXSubmit - Success!"); */
+    console.log(this.responseText);
+    /* you can get the serialized data through the "submittedData" custom property: */
+    /* console.log(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) {
+        /* NOTE: this will submit _all_ submit buttons. Detecting the correct one is non-trivial. */
+        /* 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 this, create a page named register.php (which is the action attribute of these sample forms), and put the following minimalistic content:

+ +
<?php
+/* register.php */
+
+header("Content-type: text/plain");
+
+/*
+NOTE: You should never use `print_r()` in production scripts, or
+otherwise output client-submitted data without sanitizing it first.
+Failing to sanitize can lead to cross-site scripting vulnerabilities.
+*/
+
+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 to activate this script is simply:

+ +
AJAXSubmit(myForm);
+ +
Note: This framework uses the {{domxref("FileReader")}} API to transmit file uploads. This is a recent API and is not implemented in IE9 or below. For this reason, the AJAX-only upload is considered an experimental technique. If you do not need to upload binary files, this framework works fine in most browsers.
+ +
Note: The best way to send binary content is via {{jsxref("ArrayBuffer", "ArrayBuffers")}} or {{domxref("Blob", "Blobs")}} in conjuncton with the {{domxref("XMLHttpRequest.send()", "send()")}} method and possibly the {{domxref("FileReader.readAsArrayBuffer()", "readAsArrayBuffer()")}} method of the FileReader API. But, since the aim of this script is to work with a stringifiable raw data, we used the {{domxref("XMLHttpRequest.sendAsBinary()", "sendAsBinary()")}} method in conjunction with the {{domxref("FileReader.readAsBinaryString()", "readAsBinaryString()")}} method of the FileReader API. As such, the above script makes sense only when you are dealing with small files. If you do not intend to upload binary content, consider instead using the FormData API.
+ +
Note: The non-standard sendAsBinary method is considered deprecated as of Gecko 31 {{geckoRelease(31)}} and will be removed soon. The standard send(Blob data) method can be used instead.
+ +

Using FormData objects

+ +

The {{domxref("XMLHttpRequest.FormData", "FormData")}} constructor lets you compile a set of key/value pairs to send using XMLHttpRequest. Its primary use is in sending form data, but can also be used independently from a form in order to transmit user keyed data. The transmitted data is in the same format the form's submit() method uses to send 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 purposes here is a translation of the previous example transformed to use the FormData API. Note the brevity of the code:

+ +
+
<!doctype html>
+<html>
+<head>
+<meta http-equiv="Content-Type" charset="UTF-8" />
+<title>Sending forms with FormData &ndash; MDN</title>
+<script>
+"use strict";
+
+function ajaxSuccess () {
+  console.log(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);
+    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, {{domxref("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 {{domxref("FileReader")}} API also: files are automatically loaded and uploaded.
+ +

Get last modified date

+ +
function getHeaderTime () {
+  console.log(this.getResponseHeader("Last-Modified"));  /* A valid GMTString date or null */
+}
+
+var oReq = new XMLHttpRequest();
+oReq.open("HEAD" /* use HEAD if you only need the headers! */, "yourpage.html");
+oReq.onload = getHeaderTime;
+oReq.send();
+ +

Do something when last modified date changes

+ +

Let's create two functions:

+ +
function getHeaderTime () {
+  var nLastVisit = parseFloat(window.localStorage.getItem('lm_' + this.filepath));
+  var nLastModif = Date.parse(this.getResponseHeader("Last-Modified"));
+
+  if (isNaN(nLastVisit) || nLastModif > nLastVisit) {
+    window.localStorage.setItem('lm_' + this.filepath, Date.now());
+    isFinite(nLastVisit) && this.callback(nLastModif, nLastVisit);
+  }
+}
+
+function ifHasChanged(sURL, fCallback) {
+  var oReq = new XMLHttpRequest();
+  oReq.open("HEAD" /* use HEAD - we only need the headers! */, sURL);
+  oReq.callback = fCallback;
+  oReq.filepath = sURL;
+  oReq.onload = getHeaderTime;
+  oReq.send();
+}
+ +

And to test:

+ +
/* Let's test the file "yourpage.html"... */
+
+ifHasChanged("yourpage.html", function (nModif, nVisit) {
+  console.log("The page '" + this.filepath + "' has been changed on " + (new Date(nModif)).toLocaleString() + "!");
+});
+ +

If you want to know if the current page has changed, please read the article about {{domxref("document.lastModified")}}.

+ +

Cross-site XMLHttpRequest

+ +

Modern browsers support cross-site requests by implementing the Cross-Origin Resource Sharing (CORS) 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 appending 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
+
+ +

As 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());
+oReq.send(null);
+ +

Security

+ +

{{fx_minversion_note(3, "Versions of Firefox prior to Firefox 3 allowed you to set the preference capability.policy.<policyname>.XMLHttpRequest.open</policyname> 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 conclude with an XMLHttpRequest receiving status=0 and statusText=null, this means 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 subsequently open(). This case can happen, for example, when one has an XMLHttpRequest that gets fired on an onunload event for a window, the expected XMLHttpRequest is created when the window to be closed is still there, and finally sending the request (in otherwords, open()) when this window has lost its focus and another window gains focus. The most effective way to avoid this problem is to set a listener on the new window's {{event("activate")}} event which is set once the terminated window has its {{event("unload")}} event triggered.

+ +

Workers

+ +

Setting overrideMimeType does not work from a {{domxref("Worker")}}. See {{bug(678057)}} for more details. Other browsers may handle this differently.

+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('XMLHttpRequest')}}{{Spec2('XMLHttpRequest')}}Live standard, latest version
+ +

Browser compatibility

+ + + +

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

+ +

Siehe auch

+ +
    +
  1. MDN AJAX Einführung
  2. +
  3. HTML in XMLHttpRequest
  4. +
  5. HTTP-Zugriffskontrolle
  6. +
  7. So überprüfen Sie den Sicherheitsstatus einer XMLHTTPRequest über SSL
  8. +
  9. XMLHttpRequest - REST und die Rich User Experience
  10. +
  11. Microsoft-Dokumentation
  12. +
  13. "Verwenden des XMLHttpRequest-Objekts" (jibbering.com)
  14. +
  15. Das XMLHttpRequestObjekt: WHATWG-Spezifikation
  16. +
-- cgit v1.2.3-54-g00ecf