From 3d809d2737f9b0fe0ef0f3d26c8c785d9d95cd09 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Thu, 15 Jul 2021 13:33:44 -0400 Subject: delete pages that were never translated from en-US (de, part 2) (#1552) --- .../accessibility/understanding_wcag/index.html | 59 -- .../xmlhttprequest/using_xmlhttprequest/index.html | 788 --------------------- files/de/web/html/attributes/index.html | 662 ----------------- files/de/web/http/headers/set-cookie/index.html | 223 ------ .../object/defineproperty/index.html | 413 ----------- 5 files changed, 2145 deletions(-) delete mode 100644 files/de/web/accessibility/understanding_wcag/index.html delete mode 100644 files/de/web/api/xmlhttprequest/using_xmlhttprequest/index.html delete mode 100644 files/de/web/html/attributes/index.html delete mode 100644 files/de/web/http/headers/set-cookie/index.html delete mode 100644 files/de/web/javascript/reference/global_objects/object/defineproperty/index.html (limited to 'files/de/web') diff --git a/files/de/web/accessibility/understanding_wcag/index.html b/files/de/web/accessibility/understanding_wcag/index.html deleted file mode 100644 index fe71b20ebc..0000000000 --- a/files/de/web/accessibility/understanding_wcag/index.html +++ /dev/null @@ -1,59 +0,0 @@ ---- -title: Understanding the Web Content Accessibility Guidelines -slug: Web/Accessibility/Understanding_WCAG -tags: - - NeedsTranslation - - TopicStub - - WCAG - - Web Content Accessibility Guidelines -translation_of: Web/Accessibility/Understanding_WCAG ---- -

This set of articles provides quick explanations to help you understand the steps that need to be taken to conform to the recommendations outlined in the W3C Web Content Accessibility Guidelines 2.0 or 2.1 (or just WCAG, for the purposes of this writing).

- -

The WCAG 2.0 and 2.1 provide a detailed set of guidelines for making web content more accessible to people with a wide variety of disabilities. It is comprehensive but incredibly detailed, and quite difficult to gain a rapid understanding of. For this reason, we have summarised the practical steps you need to take to satisfy the different recommendations, with further links to more details where required.

- -

The four principles

- -

WCAG is broadly broken down into four principles — major things that web content must be to be considered accessible (see Understanding the Four Principles of Accessibility for the WCAG definitions).

- -

Each of the links below will take you to pages that further expand on these areas, giving you practical advice on how to write your web content so it conforms to the success criteria outlined in each of the WCAG 2.0 and 2.1 guidelines that further sub-divides each principle.

- - - -

Should I use WCAG 2.0 or 2.1?

- -

WCAG 2.1 is the most recent and relevant accessibility standard. Use WCAG 2.1 to help more people with disabilities and reduce the future legal risk for web site owners. Target WCAG 2.0 first when allocating resources. Then step up to WCAG 2.1. 

- -

What is WCAG 2.1?

- -

WCAG 2.1 was published as an official recommendation on 05 June 2018. The European Union (EU) adopted WCAG 2.1 as the digital accessibility standard in September 2018. W3C published a press release WCAG 2.1 Adoption in Europe

- -

WCAG 2.1 includes:

- - - - - -

This guide is intended to provide practical information to help you build better, more accessible websites. However, we are not lawyers, and none of this constitutes legal advice. If you are worried about the legal implications of web accessibility, we'd recommend that you check the specific legislation governing accessibility for the web/public resources in your country or locale, and seek the advice of a qualified lawyer.

- -

What is accessibility? and particularity the Accessibility guidelines and the law section provide more related information.

diff --git a/files/de/web/api/xmlhttprequest/using_xmlhttprequest/index.html b/files/de/web/api/xmlhttprequest/using_xmlhttprequest/index.html deleted file mode 100644 index 5e1287ddac..0000000000 --- a/files/de/web/api/xmlhttprequest/using_xmlhttprequest/index.html +++ /dev/null @@ -1,788 +0,0 @@ ---- -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. -
diff --git a/files/de/web/html/attributes/index.html b/files/de/web/html/attributes/index.html deleted file mode 100644 index 3ec9df8ec7..0000000000 --- a/files/de/web/html/attributes/index.html +++ /dev/null @@ -1,662 +0,0 @@ ---- -title: HTML attribute reference -slug: Web/HTML/Attributes -tags: - - Anfänger - - Attribute - - Einstellungen - - Elemente - - HTML - - Reference - - Web -translation_of: Web/HTML/Attributes ---- -

Elemente in HTML haben Attribute; dies sind zusätzliche Werte, die die Elemente konfigurieren oder ihr Verhalten auf verschiedene Weise anpassen, um die Kriterien zu erfüllen, die die Benutzer wollen.

- -

Attributliste

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
AttributnameElementeBeschreibung
accept{{ HTMLElement("form") }}, {{ HTMLElement("input") }}Liste der Typen, die der Server akzeptiert, in der Regel ein Dateityp.
accept-charset{{ HTMLElement("form") }}Liste der unterstützten Zeichensätze.
accesskeyGlobales AttributDefiniert eine Tastenkombination zum Aktivieren oder Hinzufügen von Fokus auf das Element.
action{{ HTMLElement("form") }}Die URI eines Programms, das die über das Formular übermittelten Informationen verarbeitet.
align{{ HTMLElement("applet") }}, {{ HTMLElement("caption") }}, {{ HTMLElement("col") }}, {{ HTMLElement("colgroup") }},  {{ HTMLElement("hr") }}, {{ HTMLElement("iframe") }}, {{ HTMLElement("img") }}, {{ HTMLElement("table") }}, {{ HTMLElement("tbody") }},  {{ HTMLElement("td") }},  {{ HTMLElement("tfoot") }} , {{ HTMLElement("th") }}, {{ HTMLElement("thead") }}, {{ HTMLElement("tr") }}Gibt die horizontale Ausrichtung des Elements an.
alt{{ HTMLElement("applet") }}, {{ HTMLElement("area") }}, {{ HTMLElement("img") }}, {{ HTMLElement("input") }}Alternativer Text, falls ein Bild oder ein vergleichbares anderes Element nicht angezeigt werden kann.
async{{ HTMLElement("script") }}Gibt an, dass das Skript asynchron ausgeführt werden soll.
autocomplete{{ HTMLElement("form") }}, {{ HTMLElement("input") }}Gibt an, ob die Kontrollen in diesem Formular standardmäßig ihre Werte automatisch durch den Browser vervollständigen können.
autofocus{{ HTMLElement("button") }}, {{ HTMLElement("input") }}, {{ HTMLElement("keygen") }}, {{ HTMLElement("select") }}, {{ HTMLElement("textarea") }}Das Element sollte nach der geladenen Seite automatisch fokussiert werden.
autoplay{{ HTMLElement("audio") }}, {{ HTMLElement("video") }}Das Audio oder Video sollte so schnell wie möglich spielen.
autosave{{ HTMLElement("input") }}Bisherige Werte sollten Dropdowns von auswählbaren Werten über Seitenlasten bestehen bleiben.
bgcolor{{ HTMLElement("body") }}, {{ HTMLElement("col") }}, {{ HTMLElement("colgroup") }}, {{ HTMLElement("marquee") }}, {{ HTMLElement("table") }}, {{ HTMLElement("tbody") }}, {{ HTMLElement("tfoot") }}, {{ HTMLElement("td") }}, {{ HTMLElement("th") }}, {{ HTMLElement("tr") }} -

Hintergrundfarbe des Elements

- -
-

Hinweis: Dies ist ein veraltetes Attribut. Bitte benutze stattdessen die CSS {{ Cssxref("background-color") }} Eigenschachaft.

-
-
border{{ HTMLElement("img") }}, {{ HTMLElement("object") }}, {{ HTMLElement("table") }} -

Die Randbreite eines Elements

- -
-

Hinweis: Die ist ein veraltetes Attribut. Bitte benutze stattdessen die CSS {{ Cssxref("border") }} Eigenschaft.

-
-
buffered{{ HTMLElement("audio") }}, {{ HTMLElement("video") }}Enthält den Zeitbereich von bereits gepufferten Medien.
challenge{{ HTMLElement("keygen") }}Eine Herausforderung, die zusammen mit dem öffentlichen Schlüssel eingereicht wird.
charset{{ HTMLElement("meta") }}, {{ HTMLElement("script") }}Deklariert die Zeichencodierung der Seite oder des Skripts.
checked{{ HTMLElement("command") }}, {{ HTMLElement("input") }}Gibt an, ob das Element auf Seitenladung überprüft werden soll.
cite{{ HTMLElement("blockquote") }}, {{ HTMLElement("del") }}, {{ HTMLElement("ins") }}, {{ HTMLElement("q") }}Enthält einen URI, der auf die Quelle des Angebots oder der Änderung verweist.
classGlobales AttributOft mit CSS verwendet, um Elemente mit gemeinsamen Eigenschaften zu gestalten.
code{{ HTMLElement("applet") }}Gibt die URL der zu ladenden und ausgeführten Klassendatei des Applets an.
codebase{{ HTMLElement("applet") }}Dieses Attribut gibt die absolute oder relative URL des Verzeichnisses an, in dem Applets '.class-Dateien, die durch das Codeattribut referenziert werden, gespeichert sind.
color{{ HTMLElement("basefont") }}, {{ HTMLElement("font") }}, {{ HTMLElement("hr") }} -

Dieses Attribut setzt die Textfarbe entweder mit einer benannten Farbe oder einer Farbe, die im hexadezimalen #RRGGBB-Format angegeben ist.

- -
-

Hinweis: Das ist ein veraltetestes Attribut. Bitte benutze stattdessen die CSS {{ Cssxref("color") }} Eigenschaft.

-
-
cols{{ HTMLElement("textarea") }}Definiert die Anzahl der Spalten in einem Textbereich.
colspan{{ HTMLElement("td") }}, {{ HTMLElement("th") }}Das colspan-Attribut definiert die Anzahl der Spalten, die eine Zelle überspannen soll.
content{{ HTMLElement("meta") }}Ein Wert, der mit http-equiv oder dem Namen verbunden ist, abhängig vom Kontext.
contenteditableGlobales AttributGibt an, ob der Inhalt des Elements bearbeitet werden kann.
contextmenuGlobales AttributDefiniert die ID eines {{HTMLElement("menu")}} - Elements, das als Kontextmenü des Elements dient.
controls{{ HTMLElement("audio") }}, {{ HTMLElement("video") }}Gibt an, ob der Browser dem Benutzer die Wiedergabesteuerung anzeigen soll.
coords{{ HTMLElement("area") }}Ein Satz von Werten, die die Koordinaten des Hot-Spot-Bereichs angeben.
crossorigin{{ HTMLElement("audio") }}, {{ HTMLElement("img") }}, {{ HTMLElement("link") }}, {{ HTMLElement("script") }}, {{ HTMLElement("video") }}Wie das Element grenzüberschreitende Anfragen behandelt.
data{{ HTMLElement("object") }}Gibt die URL der Ressource an.
data-*Globales AttributErmöglicht es Ihnen, benutzerdefinierte Attribute an ein HTML-Element anzuhängen.
datetime{{ HTMLElement("del") }}, {{ HTMLElement("ins") }}, {{ HTMLElement("time") }}Gibt das Datum und die Uhrzeit an, die dem Element zugeordnet sind.
default{{ HTMLElement("track") }}Zeigt an, dass die Spur aktiviert werden soll, es sei denn, die Einstellungen des Benutzers zeigen etwas anderes an.
defer{{ HTMLElement("script") }}Gibt an, dass das Skript nach dem Analysieren der Seite ausgeführt werden soll.
dirGlobales AttributDefiniert die Textrichtung. Zulässige Werte sind (links-nach-rechts oder rechts-nach-links)
dirname{{ HTMLElement("input") }}, {{ HTMLElement("textarea") }}
disabled{{ HTMLElement("button") }}, {{ HTMLElement("command") }}, {{ HTMLElement("fieldset") }}, {{ HTMLElement("input") }}, {{ HTMLElement("keygen") }}, {{ HTMLElement("optgroup") }}, {{ HTMLElement("option") }}, {{ HTMLElement("select") }}, {{ HTMLElement("textarea") }}Gibt an, ob der Benutzer mit dem Element interagieren kann.
download{{ HTMLElement("a") }}, {{ HTMLElement("area") }}Zeigt an, dass der Hyperlink zum Herunterladen einer Ressource verwendet werden soll.
draggableGlobales AttributLegt fest, ob das Element gezogen werden kann.
dropzoneGlobales AttributGibt an, dass das Element das Fallenlassen von Inhalt auf ihm akzeptiert.
enctype{{ HTMLElement("form") }}Definiert den Inhaltstyp des Formulars, wenn die Methode POST ist.
for{{ HTMLElement("label") }}, {{ HTMLElement("output") }}Beschreibt Elemente, die zu diesem gehören.
form{{ HTMLElement("button") }}, {{ HTMLElement("fieldset") }}, {{ HTMLElement("input") }}, {{ HTMLElement("keygen") }}, {{ HTMLElement("label") }}, {{ HTMLElement("meter") }}, {{ HTMLElement("object") }}, {{ HTMLElement("output") }}, {{ HTMLElement("progress") }}, {{ HTMLElement("select") }}, {{ HTMLElement("textarea") }}Gibt das Formular an, das der Besitzer des Elements ist.
formaction{{ HTMLElement("input") }}, {{ HTMLElement("button") }}Gibt die Aktion des Elements an und überschreibt die im {{HTMLElement ("Formular")}} definierte Aktion.
headers{{ HTMLElement("td") }}, {{ HTMLElement("th") }}IDs der <th> -Elemente, die für dieses Element gelten.
height{{ HTMLElement("canvas") }}, {{ HTMLElement("embed") }}, {{ HTMLElement("iframe") }}, {{ HTMLElement("img") }}, {{ HTMLElement("input") }}, {{ HTMLElement("object") }}, {{ HTMLElement("video") }} -

Gibt die Höhe der hier aufgeführten Elemente an. Für alle anderen Elemente verwenden Sie die Eigenschaft CSS {{cssxref ("height")}}.

- -
-

Hinweis: In einigen Fällen wie {{HTMLElement ("div")}} ist dies ein Legacy-Attribut, in welchem ​​Fall die CSS {{Cssxref ("height")}} Eigenschaft stattdessen verwendet werden soll.

-
-
hiddenGlobales AttributVerhindert das Rendering des gegebenen Elements, während Kinderelemente, z.B. Script-Elemente, aktiv.
high{{ HTMLElement("meter") }}Zeigt die untere Schranke des oberen Bereichs an.
href{{ HTMLElement("a") }}, {{ HTMLElement("area") }}, {{ HTMLElement("base") }}, {{ HTMLElement("link") }}Gibt die URL einer verknüpften Ressource an.
hreflang{{ HTMLElement("a") }}, {{ HTMLElement("area") }}, {{ HTMLElement("link") }}Gibt die Sprache der verknüpften Ressource an.
http-equiv{{ HTMLElement("meta") }}
icon{{ HTMLElement("command") }}Gibt ein Bild an, das den Befehl darstellt.
idGlobales AttributOft mit CSS verwendet, um ein bestimmtes Element zu stylen. Der Wert dieses Attributs muss eindeutig sein.
integrity{{ HTMLElement("link") }}, {{ HTMLElement("script") }}  -

Sicherheits-Feature, das Browsern ermöglicht zu verifizieren, was sie abrufen.

- -

MDN Link

-
ismap{{ HTMLElement("img") }}Gibt an, dass das Bild Teil einer Server-seitigen Image-Map ist.
itempropGlobales Attribut
keytype{{ HTMLElement("keygen") }}Spezifiziert den Typ des generierten Schlüssels.
kind{{ HTMLElement("track") }}Spezifiziert die Art der Textspur.
label{{ HTMLElement("track") }}Definiert einen für den Nutzer lesbaren Titel der Textspur.
langGlobales AttributDefiniert die im Element genutzte Sprache.
language{{ HTMLElement("script") }}Definiert die im Element genutzte Skriptsprache.
list{{ HTMLElement("input") }}Identifiziert eine dem Nutzer vorzuschlagende Liste vordefinierter Optionen.
loop{{ HTMLElement("audio") }}, {{ HTMLElement("bgsound") }}, {{ HTMLElement("marquee") }}, {{ HTMLElement("video") }}Gibt an, ob das Medium ab dem Start beginnen soll, wenn es fertig ist.
low{{ HTMLElement("meter") }}Zeigt die obere Schranke des unteren Bereiches an.
manifest{{ HTMLElement("html") }}Gibt die URL des Cache-Manifests des Dokuments an.
max{{ HTMLElement("input") }}, {{ HTMLElement("meter") }}, {{ HTMLElement("progress") }}Gibt den maximal zulässigen Wert an.
maxlength{{ HTMLElement("input") }}, {{ HTMLElement("textarea") }}Definiert die maximal zulässige Anzahl von Zeichen im Element.
media{{ HTMLElement("a") }}, {{ HTMLElement("area") }}, {{ HTMLElement("link") }}, {{ HTMLElement("source") }}, {{ HTMLElement("style") }}Gibt einen Hinweis auf das Medium an, für das die verknüpfte Ressource entworfen wurde.
method{{ HTMLElement("form") }}Legt fest, welche HTTP-Methode bei der Übermittlung des Formulars verwendet werden soll. Kann GET (Standard) oder POST sein.
min{{ HTMLElement("input") }}, {{ HTMLElement("meter") }}Gibt den zulässigen Mindestwert an.
multiple{{ HTMLElement("input") }}, {{ HTMLElement("select") }}Gibt an, ob mehrere Werte in einer Eingabe des Typs E-Mail oder Datei eingegeben werden können.
muted{{ HTMLElement("video") }}Zeigt an, ob der Ton anfänglich auf Seitenladung ausgeschaltet wird.
name{{ HTMLElement("button") }}, {{ HTMLElement("form") }}, {{ HTMLElement("fieldset") }}, {{ HTMLElement("iframe") }}, {{ HTMLElement("input") }}, {{ HTMLElement("keygen") }}, {{ HTMLElement("object") }}, {{ HTMLElement("output") }}, {{ HTMLElement("select") }}, {{ HTMLElement("textarea") }}, {{ HTMLElement("map") }}, {{ HTMLElement("meta") }}, {{ HTMLElement("param") }}Name des Elements. Zum Beispiel von dem Server verwendet, um die Felder in Form zu übermitteln.
novalidate{{ HTMLElement("form") }}Dieses Attribut gibt an, dass das Formular bei der Übermittlung nicht validiert werden darf.
open{{ HTMLElement("details") }}Gibt an, ob die Details auf Seite geladen werden sollen.
optimum{{ HTMLElement("meter") }}Zeigt den optimalen numerischen Wert an.
pattern{{ HTMLElement("input") }}Definiert einen regulären Ausdruck, den der Wert des Elements validiert.
ping{{ HTMLElement("a") }}, {{ HTMLElement("area") }}
placeholder{{ HTMLElement("input") }}, {{ HTMLElement("textarea") }}Bietet dem Benutzer einen Hinweis darauf, was im Feld eingegeben werden kann.
poster{{ HTMLElement("video") }}Eine URL, die einen Posterrahmen anzeigt, bis der Benutzer spielt oder sucht.
preload{{ HTMLElement("audio") }}, {{ HTMLElement("video") }}Indicates whether the whole resource, parts of it or nothing should be preloaded.
radiogroup{{ HTMLElement("command") }}
readonly{{ HTMLElement("input") }}, {{ HTMLElement("textarea") }}Indicates whether the element can be edited.
rel{{ HTMLElement("a") }}, {{ HTMLElement("area") }}, {{ HTMLElement("link") }}Specifies the relationship of the target object to the link object.
required{{ HTMLElement("input") }}, {{ HTMLElement("select") }}, {{ HTMLElement("textarea") }}Indicates whether this element is required to fill out or not.
reversed{{ HTMLElement("ol") }}Indicates whether the list should be displayed in a descending order instead of a ascending.
rows{{ HTMLElement("textarea") }}Defines the number of rows in a text area.
rowspan{{ HTMLElement("td") }}, {{ HTMLElement("th") }}Defines the number of rows a table cell should span over.
sandbox{{ HTMLElement("iframe") }}
scope{{ HTMLElement("th") }}
scoped{{ HTMLElement("style") }}
seamless{{ HTMLElement("iframe") }}
selected{{ HTMLElement("option") }}Defines a value which will be selected on page load.
shape{{ HTMLElement("a") }}, {{ HTMLElement("area") }}
size{{ HTMLElement("input") }}, {{ HTMLElement("select") }}Defines the width of the element (in pixels). If the element's type attribute is text or password then it's the number of characters.
sizes{{ HTMLElement("link") }}, {{ HTMLElement("img") }}, {{ HTMLElement("source") }}
slotGlobales AttributAssigns a slot in a shadow DOM shadow tree to an element.
span{{ HTMLElement("col") }}, {{ HTMLElement("colgroup") }}
spellcheckGlobales AttributIndicates whether spell checking is allowed for the element.
src{{ HTMLElement("audio") }}, {{ HTMLElement("embed") }}, {{ HTMLElement("iframe") }}, {{ HTMLElement("img") }}, {{ HTMLElement("input") }}, {{ HTMLElement("script") }}, {{ HTMLElement("source") }}, {{ HTMLElement("track") }}, {{ HTMLElement("video") }}Die URL des einbettbaren Inhalts.
srcdoc{{ HTMLElement("iframe") }}
srclang{{ HTMLElement("track") }}
srcset{{ HTMLElement("img") }}
start{{ HTMLElement("ol") }}Definiert die erste Zahl, wenn sie anders als 1 ist.
step{{ HTMLElement("input") }}
styleGlobales AttributDefiniert CSS Stile für das Element und überschreibt andere Stile, welche z.B. in einem Stylesheet für das Element festgelegt sind.
summary{{ HTMLElement("table") }}
tabindexGlobales AttributOverrides the browser's default tab order and follows the one specified instead.
target{{ HTMLElement("a") }}, {{ HTMLElement("area") }}, {{ HTMLElement("base") }}, {{ HTMLElement("form") }}
titleGlobales AttributText to be displayed in a tooltip when hovering over the element.
type{{ HTMLElement("button") }}, {{ HTMLElement("input") }}, {{ HTMLElement("command") }}, {{ HTMLElement("embed") }}, {{ HTMLElement("object") }}, {{ HTMLElement("script") }}, {{ HTMLElement("source") }}, {{ HTMLElement("style") }}, {{ HTMLElement("menu") }}Definiert den Typ eines Elements.
usemap{{ HTMLElement("img") }},  {{ HTMLElement("input") }}, {{ HTMLElement("object") }}
value{{ HTMLElement("button") }}, {{ HTMLElement("option") }}, {{ HTMLElement("input") }}, {{ HTMLElement("li") }}, {{ HTMLElement("meter") }}, {{ HTMLElement("progress") }}, {{ HTMLElement("param") }}Defines a default value which will be displayed in the element on page load.
width{{ HTMLElement("canvas") }}, {{ HTMLElement("embed") }}, {{ HTMLElement("iframe") }}, {{ HTMLElement("img") }}, {{ HTMLElement("input") }}, {{ HTMLElement("object") }}, {{ HTMLElement("video") }} -

For the elements listed here, this establishes the element's width.

- -
-

Note: For all other instances, such as {{ HTMLElement("div") }}, this is a legacy attribute, in which case the CSS {{ Cssxref("width") }} property should be used instead.

-
-
wrap{{ HTMLElement("textarea") }}Indicates whether the text should be wrapped.
- -

Content versus IDL attributes

- -

In HTML, most attributes have two faces: the content attribute and the IDL attribute.

- -

The content attribute is the attribute as you set it from the content (the HTML code) and you can set it or get it via {{domxref("element.setAttribute()")}} or {{domxref("element.getAttribute()")}}. The content attribute is always a string even when the expected value should be an integer. For example, to set an {{HTMLElement("input")}} element's maxlength to 42 using the content attribute, you have to call setAttribute("maxlength", "42") on that element.

- -

The IDL attribute is also known as a JavaScript property. These are the attributes you can read or set using JavaScript properties like element.foo. The IDL attribute is always going to use (but might transform) the underlying content attribute to return a value when you get it and is going to save something in the content attribute when you set it. In other words, the IDL attributes, in essence, reflect the content attributes.

- -

Most of the time, IDL attributes will return their values as they are really used. For example, the default type for {{HTMLElement("input")}} elements is "text", so if you set input.type="foobar", the <input> element will be of type text (in the appearance and the behavior) but the "type" content attribute's value will be "foobar". However, the type IDL attribute will return the string "text".

- -

IDL attributes are not always strings; for example, input.maxlength is a number (a signed long). When using IDL attributes, you read or set values of the desired type, so input.maxlength is always going to return a number and when you set input.maxlength ,it wants a number. If you pass another type, it is automatically converted to a number as specified by the standard JavaScript rules for type conversion.

- -

IDL attributes can reflect other types such as unsigned long, URLs, booleans, etc. Unfortunately, there are no clear rules and the way IDL attributes behave in conjunction with their corresponding content attributes depends on the attribute. Most of the time, it will follow the rules laid out in the specification, but sometimes it doesn't. HTML specifications try to make this as developer-friendly as possible, but for various reasons (mostly historical), some attributes  behave oddly (select.size, for example) and you should read the specifications to understand how exactly they behave.

- -

Siehe auch

- - diff --git a/files/de/web/http/headers/set-cookie/index.html b/files/de/web/http/headers/set-cookie/index.html deleted file mode 100644 index d82bd2a816..0000000000 --- a/files/de/web/http/headers/set-cookie/index.html +++ /dev/null @@ -1,223 +0,0 @@ ---- -title: Set-Cookie -slug: Web/HTTP/Headers/Set-Cookie -tags: - - Cookies - - HTTP - - NeedsTranslation - - Reference - - Response - - TopicStub - - header - - samesite -translation_of: Web/HTTP/Headers/Set-Cookie ---- -
{{HTTPSidebar}}
- -

The Set-Cookie HTTP response header is used to send a cookie from the server to the user agent, so the user agent can send it back to the server later. To send multiple cookies, multiple Set-Cookie headers should be sent in the same response.

- -
-

Browsers block frontend JavaScript code from accessing the Set Cookie header, as required by the Fetch spec, which defines Set-Cookie as a forbidden response-header name that must be filtered out from any response exposed to frontend code.

-
- -

For more information, see the guide on Using HTTP cookies.

- - - - - - - - - - - - - - - - -
Header type{{Glossary("Response header")}}
{{Glossary("Forbidden header name")}}no
Forbidden response-header nameyes
- -

Syntax

- -
Set-Cookie: <cookie-name>=<cookie-value>
-Set-Cookie: <cookie-name>=<cookie-value>; Expires=<date>
-Set-Cookie: <cookie-name>=<cookie-value>; Max-Age=<non-zero-digit>
-Set-Cookie: <cookie-name>=<cookie-value>; Domain=<domain-value>
-Set-Cookie: <cookie-name>=<cookie-value>; Path=<path-value>
-Set-Cookie: <cookie-name>=<cookie-value>; Secure
-Set-Cookie: <cookie-name>=<cookie-value>; HttpOnly
-
-Set-Cookie: <cookie-name>=<cookie-value>; SameSite=Strict
-Set-Cookie: <cookie-name>=<cookie-value>; SameSite=Lax
-Set-Cookie: <cookie-name>=<cookie-value>; SameSite=None; Secure
-
-// Multiple attributes are also possible, for example:
-Set-Cookie: <cookie-name>=<cookie-value>; Domain=<domain-value>; Secure; HttpOnly
-
- -

Attributes

- -
-
<cookie-name>=<cookie-value>
-
A cookie begins with a name-value pair: -
    -
  • A <cookie-name> can be any US-ASCII characters, except control characters, spaces, or tabs. It also must not contain a separator character like the following: ( ) < > @ , ; : \ " / [ ] ? = { }.
  • -
  • A <cookie-value> can optionally be wrapped in double quotes and include any US-ASCII characters excluding control characters, {{glossary("Whitespace")}}, double quotes, comma, semicolon, and backslash. Encoding: Many implementations perform URL encoding on cookie values, however it is not required per the RFC specification. It does help satisfying the requirements about which characters are allowed for <cookie-value> though.
  • -
  • __Secure- prefix: Cookies names starting with __Secure- (dash is part of the prefix) must be set with the secure flag from a secure page (HTTPS).
  • -
  • __Host- prefix: Cookies with names starting with __Host- must be set with the secure flag, must be from a secure page (HTTPS), must not have a domain specified (and therefore aren't sent to subdomains) and the path must be /.
  • -
-
-
Expires=<date> {{optional_inline}}
-
-

The maximum lifetime of the cookie as an HTTP-date timestamp. See {{HTTPHeader("Date")}} for the required formatting.

- -

If unspecified, the cookie becomes a session cookie. A session finishes when the client shuts down, and session cookies will be removed.

- -
-

Warning: Many web browsers have a session restore feature that will save all tabs and restore them next time the browser is used. Session cookies will also be restored, as if the browser was never closed.

-
- -

When an Expires date is set, the deadline is relative to the client the cookie is being set on, not the server.

-
-
Max-Age=<number> {{optional_inline}}
-
Number of seconds until the cookie expires. A zero or negative number will expire the cookie immediately. If both Expires and Max-Age are set, Max-Age has precedence.
-
Domain=<domain-value> {{optional_inline}}
-
Host to which the cookie will be sent. -
    -
  • If omitted, defaults to the host of the current document URL, not including subdomains.
  • -
  • Contrary to earlier specifications, leading dots in domain names (.example.com) are ignored.
  • -
  • Multiple host/domain values are not allowed, but if a domain is specified, then subdomains are always included.
  • -
-
-
Path=<path-value> {{optional_inline}}
-
A path that must exist in the requested URL, or the browser won't send the Cookie header.
-
The forward slash (/) character is interpreted as a directory separator, and subdirectories will be matched as well: for Path=/docs, /docs, /docs/Web/, and /docs/Web/HTTP will all match.
-
Secure {{optional_inline}}
-
Cookie is only sent to the server when a request is made with the https: scheme (except on localhost), and therefore is more resistent to man-in-the-middle attacks. -

Note: Do not assume that Secure prevents all access to sensitive information in cookies (session keys, login details, etc.). Cookies with this attribute can still be read/modified with access to the client's hard disk, or from JavaScript if the HttpOnly cookie attribute is not set.

- -

Note: Insecure sites (http:) can't set cookies with the Secure attribute (since Chrome 52 and Firefox 52). For Firefox, the https: requirements are ignored when the Secure attribute is set by localhost (since Firefox 75).

-
-
HttpOnly {{optional_inline}}
-
Forbids JavaScript from accessing the cookie, for example, through the {{domxref("Document.cookie")}} property. Note that a cookie that has been created with HttpOnly will still be sent with JavaScript-initiated requests, e.g. when calling {{domxref("XMLHttpRequest.send()")}} or {{domxref("fetch()")}}. This mitigates attacks against cross-site scripting ({{Glossary("XSS")}}).
-
SameSite=<samesite-value> {{optional_inline}}
-
Controls whether a cookie is sent with cross-origin requests, providing some protection against cross-site request forgery attacks ({{Glossary("CSRF")}}).
-
-
-

Standards related to the SameSite Cookies recently changed such that:

- -
    -
  1. The cookie-sending behaviour if SameSite is not specified is SameSite=Lax. Previously the default was that cookies were sent for all requests.
  2. -
  3. Cookies with SameSite=None must now
    - also specify the Secure attribute (i.e. they require a secure context).
  4. -
- -

The options below covers the new behaviour. See the Browser compatibility table for information about specific browser implementation (rows: "SameSite: Defaults to Lax" and "SameSite: Secure context required").

-
- Inline options are: - -
    -
  • Strict: The browser sends the cookie only for same-site requests (that is, requests originating from the same site that set the cookie). If the request originated from a different URL than the current one, no cookies with the SameSite=Strict attribute are sent.
  • -
  • Lax: The cookie is not sent on cross-site requests, such as calls to load images or frames, but is sent when a user is navigating to the origin site from an external site (e.g. if following a link).
    - This is the default behaviour if the SameSite attribute is not specified.
  • -
  • None: The browser sends the cookie with both cross-site and same-site requests. The Secure attribute must also be set when SameSite=None!
  • -
-
-
- -

Examples

- - - -

Session cookies are removed when the client shuts down. Cookies are session cookies if they don't specify the Expires or Max-Age attributes.

- -
Set-Cookie: sessionId=38afes7a8
- - - -

Instead of expiring when the client is closed, permanent cookies expire at a specific date (Expires) or after a specific length of time (Max-Age).

- -
Set-Cookie: id=a3fWa; Expires=Wed, 21 Oct 2015 07:28:00 GMT
-
- -
Set-Cookie: id=a3fWa; Max-Age=2592000
- -

Invalid domains

- -

A cookie for a domain that does not include the server that set it should be rejected by the user agent.

- -

The following cookie will be rejected if set by a server hosted on originalcompany.com:

- -
Set-Cookie: qwerty=219ffwef9w0f; Domain=somecompany.co.uk
- -

A cookie for a sub domain of the serving domain will be rejected.

- -

The following cookie will be rejected if set by a server hosted on example.com:

- -
Set-Cookie: sessionId=e8bb43229de9; Domain=foo.example.com
- - - -

Cookies names prefixed with __Secure- or __Host- can be used only if they are set with the secure attribute from a secure (HTTPS) origin.

- -

In addition, cookies with the __Host- prefix must have a path of / (meaning any path at the host) and must not have a Domain attribute.

- -
-

For clients that don't implement cookie prefixes, you cannot count on these additional assurances, and prefixed cookies will always be accepted.

-
- -
// Both accepted when from a secure origin (HTTPS)
-Set-Cookie: __Secure-ID=123; Secure; Domain=example.com
-Set-Cookie: __Host-ID=123; Secure; Path=/
-
-// Rejected due to missing Secure attribute
-Set-Cookie: __Secure-id=1
-
-// Rejected due to the missing Path=/ attribute
-Set-Cookie: __Host-id=1; Secure
-
-// Rejected due to setting a Domain
-Set-Cookie: __Host-id=1; Secure; Path=/; Domain=example.com
-
- -

Specifications

- - - - - - - - - - - - - - - - - - -
SpecificationTitle
{{RFC("6265", "Set-Cookie", "4.1")}}HTTP State Management Mechanism
draft-ietf-httpbis-rfc6265bis-05Cookie Prefixes, Same-Site Cookies, and Strict Secure Cookies
- -

Browser compatibility

- -

{{Compat("http.headers.Set-Cookie", 5)}}

- -

Compatibility notes

- - - -

See also

- - diff --git a/files/de/web/javascript/reference/global_objects/object/defineproperty/index.html b/files/de/web/javascript/reference/global_objects/object/defineproperty/index.html deleted file mode 100644 index 7120abb08e..0000000000 --- a/files/de/web/javascript/reference/global_objects/object/defineproperty/index.html +++ /dev/null @@ -1,413 +0,0 @@ ---- -title: Object.defineProperty() -slug: Web/JavaScript/Reference/Global_Objects/Object/defineProperty -tags: - - Méthode - - Objekt -translation_of: Web/JavaScript/Reference/Global_Objects/Object/defineProperty ---- -
{{JSRef}}
- -

Die Methode Object.defineProperty() definiert eine neue Eigenschaft direkt auf ein Objekt, oder modifiziert eine Eigenschaft. Schließlich gibt die Funktion das Objekt zurück.

- -

Syntax

- -
Object.defineProperty(obj, prop, descriptor)
- -

Parameter

- -
-
obj
-
Das Objekt, welchem die neue Eigenschaft zugewiesen werden soll.
-
prop
-
Der Name der Eigenschaft, welche hinzugefügt oder modifiziert werden soll.
-
descriptor
-
Die Beschreibung/ der Wert, welche die neue Eigenschaft annehmen soll.
-
- -

Rückgabewert

- -

Das Objekt, welches behandelt wurde.

- -

Beschreibung

- -

Diese Methode erlaubt präzises Hinzufügen oder Modifizieren von Eigenschaften eines Objektes. Normal property addition through assignment creates properties which show up during property enumeration ({{jsxref("Statements/for...in", "for...in")}} loop or {{jsxref("Object.keys")}} method), whose values may be changed, and which may be {{jsxref("Operators/delete", "deleted", "", 1)}}. This method allows these extra details to be changed from their defaults. Standardmäßig sind Werte die mit Object.defineProperty() hinzugefügt wurden unveränderbar.

- -

Attribut Deskriptoren unterscheiden sich in zwei Varianten: Daten Deskriptoren und Zugiffsdeskriptoren. Ein Datendeskriptor ist ein Attribut welches einen Wert hat das schreibbar oder nicht schreibbar sein kann. Ein Zugriffsdeskriptor ist ein Attribut das mit einem "getter/setter Paar" beschrieben wird. Ein Deskriptor muss von einer dieser beiden Arten sein, er kann nicht beides sein.

- -

Beide, Daten- und Zugriffsdeskriptoren sind Objekte. Sie teilen die folgenden benötigten Objektschlüssel:

- -
-
configurable
-
true if and only if the type of this property descriptor may be changed and if the property may be deleted from the corresponding object.
- Defaults to false.
-
enumerable
-
true if and only if this property shows up during enumeration of the properties on the corresponding object.
- Defaults to false.
-
- -

Ein Datendeskriptor hat außerdem die folgenden, optionalen Schlüssel:

- -
-
value
-
The value associated with the property. Can be any valid JavaScript value (number, object, function, etc).
- Defaults to {{jsxref("undefined")}}.
-
writable
-
true if and only if the value associated with the property may be changed with an {{jsxref("Operators/Assignment_Operators", "assignment operator", "", 1)}}.
- Defaults to false.
-
- -

Ein Zugriffsdeskriptor hat außerdem die folgenden, optionalen Schlüssel:

- -
-
get
-
A function which serves as a getter for the property, or {{jsxref("undefined")}} if there is no getter. The function return will be used as the value of property.
- Defaults to {{jsxref("undefined")}}.
-
set
-
A function which serves as a setter for the property, or {{jsxref("undefined")}} if there is no setter. The function will receive as only argument the new value being assigned to the property.
- Defaults to {{jsxref("undefined")}}.
-
- -

Bear in mind that these options are not necessarily the descriptor's own properties, and properties inherited from the prototype chain will be considered too. In order to ensure these defaults are preserved you might freeze the {{jsxref("Object.prototype")}} upfront or specify all options explicitly.

- -
// being explicit
-Object.defineProperty(obj, 'key', {
-  enumerable: false,
-  configurable: false,
-  writable: false,
-  value: 'static'
-});
-
-// recycling same object
-function withValue(value) {
-  var d = withValue.d || (
-    withValue.d = {
-      enumerable: false,
-      writable: false,
-      configurable: false,
-      value: null
-    }
-  );
-  d.value = value;
-  return d;
-}
-// ... and ...
-Object.defineProperty(obj, 'key', withValue('static'));
-
-// if freeze is available, prevents adding or
-// removing the object prototype properties
-// (value, get, set, enumerable, writable, configurable)
-(Object.freeze || Object)(Object.prototype);
-
- -

Examples

- -

If you want to see how to use the Object.defineProperty method with a binary-flags-like syntax, see additional examples.

- -

Creating a property

- -

When the property specified doesn't exist in the object, Object.defineProperty() creates a new property as described. Fields may be omitted from the descriptor, and default values for those fields are imputed. All of the Boolean-valued fields default to false. The value, get, and set fields default to {{jsxref("undefined")}}. A property which is defined without get/set/value/writable is called “generic” and is “typed” as a data descriptor.

- -
var o = {}; // Creates a new object
-
-// Example of an object property added with defineProperty with a data property descriptor
-Object.defineProperty(o, 'a', {
-  value: 37,
-  writable: true,
-  enumerable: true,
-  configurable: true
-});
-// 'a' property exists in the o object and its value is 37
-
-// Example of an object property added with defineProperty with an accessor property descriptor
-var bValue = 38;
-Object.defineProperty(o, 'b', {
-  get: function() { return bValue; },
-  set: function(newValue) { bValue = newValue; },
-  enumerable: true,
-  configurable: true
-});
-o.b; // 38
-// 'b' property exists in the o object and its value is 38
-// The value of o.b is now always identical to bValue, unless o.b is redefined
-
-// You cannot try to mix both:
-Object.defineProperty(o, 'conflict', {
-  value: 0x9f91102,
-  get: function() { return 0xdeadbeef; }
-});
-// throws a TypeError: value appears only in data descriptors, get appears only in accessor descriptors
-
- -

Modifying a property

- -

When the property already exists, Object.defineProperty() attempts to modify the property according to the values in the descriptor and the object's current configuration. If the old descriptor had its configurable attribute set to false (the property is said to be “non-configurable”), then no attribute besides writable can be changed. In that case, it is also not possible to switch back and forth between the data and accessor property types.

- -

If a property is non-configurable, its writable attribute can only be changed to false.

- -

A {{jsxref("TypeError")}} is thrown when attempts are made to change non-configurable property attributes (besides the writable attribute) unless the current and new values are the same.

- -

Writable attribute

- -

When the writable property attribute is set to false, the property is said to be “non-writable”. It cannot be reassigned.

- -
var o = {}; // Creates a new object
-
-Object.defineProperty(o, 'a', {
-  value: 37,
-  writable: false
-});
-
-console.log(o.a); // logs 37
-o.a = 25; // No error thrown (it would throw in strict mode, even if the value had been the same)
-console.log(o.a); // logs 37. The assignment didn't work.
-
- -

As seen in the example, trying to write into the non-writable property doesn't change it but doesn't throw an error either.

- -

Enumerable attribute

- -

The enumerable property attribute defines whether the property shows up in a {{jsxref("Statements/for...in", "for...in")}} loop and {{jsxref("Object.keys()")}} or not.

- -
var o = {};
-Object.defineProperty(o, 'a', { value: 1, enumerable: true });
-Object.defineProperty(o, 'b', { value: 2, enumerable: false });
-Object.defineProperty(o, 'c', { value: 3 }); // enumerable defaults to false
-o.d = 4; // enumerable defaults to true when creating a property by setting it
-
-for (var i in o) {
-  console.log(i);
-}
-// logs 'a' and 'd' (in undefined order)
-
-Object.keys(o); // ['a', 'd']
-
-o.propertyIsEnumerable('a'); // true
-o.propertyIsEnumerable('b'); // false
-o.propertyIsEnumerable('c'); // false
-
- -

Configurable attribute

- -

The configurable attribute controls at the same time whether the property can be deleted from the object and whether its attributes (other than writable) can be changed.

- -
var o = {};
-Object.defineProperty(o, 'a', {
-  get: function() { return 1; },
-  configurable: false
-});
-
-Object.defineProperty(o, 'a', { configurable: true }); // throws a TypeError
-Object.defineProperty(o, 'a', { enumerable: true }); // throws a TypeError
-Object.defineProperty(o, 'a', { set: function() {} }); // throws a TypeError (set was undefined previously)
-Object.defineProperty(o, 'a', { get: function() { return 1; } }); // throws a TypeError (even though the new get does exactly the same thing)
-Object.defineProperty(o, 'a', { value: 12 }); // throws a TypeError
-
-console.log(o.a); // logs 1
-delete o.a; // Nothing happens
-console.log(o.a); // logs 1
-
- -

If the configurable attribute of o.a had been true, none of the errors would be thrown and the property would be deleted at the end.

- -

Adding properties and default values

- -

It's important to consider the way default values of attributes are applied. There is often a difference between simply using dot notation to assign a value and using Object.defineProperty(), as shown in the example below.

- -
var o = {};
-
-o.a = 1;
-// is equivalent to:
-Object.defineProperty(o, 'a', {
-  value: 1,
-  writable: true,
-  configurable: true,
-  enumerable: true
-});
-
-
-// On the other hand,
-Object.defineProperty(o, 'a', { value: 1 });
-// is equivalent to:
-Object.defineProperty(o, 'a', {
-  value: 1,
-  writable: false,
-  configurable: false,
-  enumerable: false
-});
-
- -

Custom Setters and Getters

- -

Example below shows how to implement a self-archiving object. When temperature property is set, the archive array gets a log entry.

- -
function Archiver() {
-  var temperature = null;
-  var archive = [];
-
-  Object.defineProperty(this, 'temperature', {
-    get: function() {
-      console.log('get!');
-      return temperature;
-    },
-    set: function(value) {
-      temperature = value;
-      archive.push({ val: temperature });
-    }
-  });
-
-  this.getArchive = function() { return archive; };
-}
-
-var arc = new Archiver();
-arc.temperature; // 'get!'
-arc.temperature = 11;
-arc.temperature = 13;
-arc.getArchive(); // [{ val: 11 }, { val: 13 }]
-
- -

or

- -
var pattern = {
-    get: function () {
-        return 'I always return this string, whatever you have assigned';
-    },
-    set: function () {
-        this.myname = 'this is my name string';
-    }
-};
-
-
-function TestDefineSetAndGet() {
-    Object.defineProperty(this, 'myproperty', pattern);
-}
-
-
-var instance = new TestDefineSetAndGet();
-instance.myproperty = 'test';
-console.log(instance.myproperty); // I always return this string, whatever you have assigned
-
-console.log(instance.myname); // this is my name string
-
-
- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES5.1', '#sec-15.2.3.6', 'Object.defineProperty')}}{{Spec2('ES5.1')}}Initial definition. Implemented in JavaScript 1.8.5.
{{SpecName('ES6', '#sec-object.defineproperty', 'Object.defineProperty')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-object.defineproperty', 'Object.defineProperty')}}{{Spec2('ESDraft')}}
- -

Browser compatibility

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FeatureFirefox (Gecko)ChromeInternet ExplorerOperaSafari
Basic support{{CompatGeckoDesktop("2")}}{{CompatChrome("5")}}{{CompatIE("9")}} [1]{{CompatOpera("11.60")}}{{CompatSafari("5.1")}} [2]
-
- -
- - - - - - - - - - - - - - - - - - - -
FeatureFirefox Mobile (Gecko)AndroidIE MobileOpera MobileSafari Mobile
Basic support{{CompatGeckoMobile("2")}}{{CompatVersionUnknown}}{{CompatIE("9")}}{{CompatOperaMobile("11.5")}}{{CompatVersionUnknown}}
-
- -

[1] In Internet Explorer 8 only on DOM objects and with some non-standard behaviors.

- -

[2] Also supported in Safari 5, but not on DOM objects.

- -

Compatibility notes

- -

Redefining the length property of an Array object

- -

It is possible to redefine the {{jsxref("Array.length", "length")}} property of arrays, subject to the usual redefinition restrictions. (The {{jsxref("Array.length", "length")}} property is initially non-configurable, non-enumerable, and writable. Thus on an unaltered array it is possible to change the {{jsxref("Array.length", "length")}} property's value, or to make it non-writable. It is not allowed to change its enumerability or configurability, or if it is non-writable to change its value or writability.) However, not all browsers permit this redefinition.

- -

Firefox 4 through 22 will throw a {{jsxref("TypeError")}} on any attempt whatsoever (whether permitted or not) to redefine the {{jsxref("Array.length", "length")}} property of an array.

- -

Versions of Chrome which implement Object.defineProperty() in some circumstances ignore a length value different from the array's current {{jsxref("Array.length", "length")}} property. In some circumstances changing writability seems to silently not work (and not throw an exception). Also, relatedly, some array-mutating methods like {{jsxref("Array.prototype.push")}} don't respect a non-writable length.

- -

Versions of Safari which implement Object.defineProperty() ignore a length value different from the array's current {{jsxref("Array.length", "length")}} property, and attempts to change writability execute without error but do not actually change the property's writability.

- -

Only Internet Explorer 9 and later, and Firefox 23 and later, appear to fully and correctly implement redefinition of the {{jsxref("Array.length", "length")}} property of arrays. For now, don't rely on redefining the {{jsxref("Array.length", "length")}} property of an array to either work, or to work in a particular manner. And even when you can rely on it, there's really no good reason to do so.

- -

Internet Explorer 8 specific notes

- -

Internet Explorer 8 implemented a Object.defineProperty() method that could only be used on DOM objects. A few things need to be noted:

- - - -

See also

- - -- cgit v1.2.3-54-g00ecf