From da78a9e329e272dedb2400b79a3bdeebff387d47 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:42:17 -0500 Subject: initial commit --- files/id/web/api/abstractworker/index.html | 125 ++++ files/id/web/api/api_push/index.html | 165 +++++ files/id/web/api/cachestorage/index.html | 198 +++++ files/id/web/api/canvas_api/index.html | 172 +++++ files/id/web/api/console/index.html | 278 ++++++++ files/id/web/api/document/createelement/index.html | 225 ++++++ files/id/web/api/document/index.html | 576 +++++++++++++++ files/id/web/api/document/links/index.html | 101 +++ files/id/web/api/document/write/index.html | 77 ++ files/id/web/api/event/currenttarget/index.html | 127 ++++ files/id/web/api/event/index.html | 149 ++++ files/id/web/api/event/target/index.html | 90 +++ files/id/web/api/fetch_api/index.html | 88 +++ files/id/web/api/index.html | 12 + files/id/web/api/mobile_connection_api/index.html | 149 ++++ files/id/web/api/navigator/index.html | 149 ++++ files/id/web/api/navigator/mediadevices/index.html | 47 ++ .../id/web/api/navigator/serviceworker/index.html | 101 +++ files/id/web/api/service_worker_api/index.html | 283 ++++++++ .../using_service_workers/index.html | 539 ++++++++++++++ files/id/web/api/serviceworker/index.html | 157 ++++ files/id/web/api/serviceworkercontainer/index.html | 132 ++++ .../web/api/serviceworkerregistration/index.html | 245 +++++++ .../pushmanager/index.html | 130 ++++ files/id/web/api/speechsynthesis/index.html | 151 ++++ .../api/speechsynthesis/onvoiceschanged/index.html | 74 ++ files/id/web/api/storage/index.html | 100 +++ files/id/web/api/webgl_api/index.html | 235 ++++++ files/id/web/api/webrtc_api/index.html | 185 +++++ files/id/web/api/window/getselection/index.html | 100 +++ files/id/web/api/window/index.html | 479 +++++++++++++ files/id/web/api/window/window/index.html | 63 ++ files/id/web/api/xmlhttprequest/index.html | 200 ++++++ .../xmlhttprequest/using_xmlhttprequest/index.html | 793 +++++++++++++++++++++ 34 files changed, 6695 insertions(+) create mode 100644 files/id/web/api/abstractworker/index.html create mode 100644 files/id/web/api/api_push/index.html create mode 100644 files/id/web/api/cachestorage/index.html create mode 100644 files/id/web/api/canvas_api/index.html create mode 100644 files/id/web/api/console/index.html create mode 100644 files/id/web/api/document/createelement/index.html create mode 100644 files/id/web/api/document/index.html create mode 100644 files/id/web/api/document/links/index.html create mode 100644 files/id/web/api/document/write/index.html create mode 100644 files/id/web/api/event/currenttarget/index.html create mode 100644 files/id/web/api/event/index.html create mode 100644 files/id/web/api/event/target/index.html create mode 100644 files/id/web/api/fetch_api/index.html create mode 100644 files/id/web/api/index.html create mode 100644 files/id/web/api/mobile_connection_api/index.html create mode 100644 files/id/web/api/navigator/index.html create mode 100644 files/id/web/api/navigator/mediadevices/index.html create mode 100644 files/id/web/api/navigator/serviceworker/index.html create mode 100644 files/id/web/api/service_worker_api/index.html create mode 100644 files/id/web/api/service_worker_api/using_service_workers/index.html create mode 100644 files/id/web/api/serviceworker/index.html create mode 100644 files/id/web/api/serviceworkercontainer/index.html create mode 100644 files/id/web/api/serviceworkerregistration/index.html create mode 100644 files/id/web/api/serviceworkerregistration/pushmanager/index.html create mode 100644 files/id/web/api/speechsynthesis/index.html create mode 100644 files/id/web/api/speechsynthesis/onvoiceschanged/index.html create mode 100644 files/id/web/api/storage/index.html create mode 100644 files/id/web/api/webgl_api/index.html create mode 100644 files/id/web/api/webrtc_api/index.html create mode 100644 files/id/web/api/window/getselection/index.html create mode 100644 files/id/web/api/window/index.html create mode 100644 files/id/web/api/window/window/index.html create mode 100644 files/id/web/api/xmlhttprequest/index.html create mode 100644 files/id/web/api/xmlhttprequest/using_xmlhttprequest/index.html (limited to 'files/id/web/api') diff --git a/files/id/web/api/abstractworker/index.html b/files/id/web/api/abstractworker/index.html new file mode 100644 index 0000000000..cea5a54797 --- /dev/null +++ b/files/id/web/api/abstractworker/index.html @@ -0,0 +1,125 @@ +--- +title: AbstractWorker +slug: Web/API/AbstractWorker +translation_of: Web/API/AbstractWorker +--- +

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

+ +

Antarmuka AbstractWorker dari abstrak properti Web Workers API  dan method umum untuk semua jenis worker, berupa {{domxref("Worker")}} atau {{domxref("SharedWorker")}}.

+ +

Properti

+ +

Antarmuka AbstractWorker tidak mewarisi properti apapun.

+ +

Event handlers

+ +
+
{{domxref("AbstractWorker.onerror")}}
+
Sebuah {{ domxref("EventListener") }} yang dipanggil ketika sebuah {{domxref("ErrorEvent")}} dari tipe error bubbles melalui worker.
+
+ +

Method

+ +

Antarmuka AbstractWorker tidak menjalankan atau mewarisi method apapun.

+ +

Contoh

+ +

Catat bahwa anda tidak ingin menggunakan antarmuka AbstractWorker langsung di dalam kode anda — ketika dipanggil, {{domxref("Worker")}} dan {{domxref("SharedWorker")}} mewarisi propertinya. Pada contoh code snippet menunjukan pembuatan objek {{domxref("Worker")}} menggunakan konstruktor {{domxref("Worker.Worker", "Worker()")}} dan penggunakan dari objek:

+ +
var myWorker = new Worker("worker.js");
+
+first.onchange = function() {
+  myWorker.postMessage([first.value,second.value]);
+  console.log('Message posted to worker');
+}
+ +

Contoh lengkapnya, lihat:

+ + + +

Spesifikasi

+ + + + + + + + + + + + + + + + + + + + + +
SpesifikasiStatusComment
{{SpecName("HTML WHATWG", "#the-abstractworker-abstract-interface", "AbstractWorker")}}{{Spec2("HTML WHATWG")}}No change from {{SpecName("Web Workers")}}.
{{SpecName("Web Workers", "#the-abstractworker-abstract-interface", "AbstractWorker")}}{{Spec2("Web Workers")}}Initial definition.
+ +

Kompabilitas Browser

+ +
{{CompatibilityTable()}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FiturChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Dukungan dasar{{CompatChrome(4)}}{{CompatGeckoDesktop("1.9.1")}}1010.64
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FiturAndroidFirefox Mobile (Gecko)Firefox OS (Gecko)IE PhoneOpera MobileSafari Mobile
Dukungan dasar4.4{{CompatGeckoMobile("1.9.1")}}1.0.11011.55.1
+
+ +

Lihat Juga

+ + + +

 

diff --git a/files/id/web/api/api_push/index.html b/files/id/web/api/api_push/index.html new file mode 100644 index 0000000000..feae8a7373 --- /dev/null +++ b/files/id/web/api/api_push/index.html @@ -0,0 +1,165 @@ +--- +title: API Push +slug: Web/API/API_Push +translation_of: Web/API/Push_API +--- +
{{DefaultAPISidebar("Push API")}}{{SeeCompatTable}}
+ +

API Push memberikan aplikasi web kemampuan menerima pesan yang didorong oleh peladen ke dalam agen pengguna, baik bila aplikasi berada di permukaan atau baru dimuat. API Push memungkinkan pengembang memberikan pemberitahuan dan pembaruan tak sinkron ke pengguna yang mengizinkan. Hal ini memberikan hasil pendekatan yang lebih baik untuk muatan baru yang terus berubah.

+ +
+

Catatan: Dokumentasi ini melingkupi spesifikasi API Push W3C. Bila Anda mencari dokumentasi untuk mekanisme berpemilik dari Firefox OS, lihat Push Sederhana.

+
+ +

Push concepts and usage

+ +

For an app to receive push messages, it has to have an active service worker. When the service worker is active, it can subscribe to push notifications using {{domxref("PushManager.subscribe()")}}.

+ +

The resulting {{domxref("PushSubscription")}} includes all the information that the application needs to send a push message: an endpoint and the encryption key needed for sending data.

+ +

The service worker will be started as necessary to handle incoming push messages, which are delivered to the {{domxref("ServiceWorkerGlobalScope.onpush")}} event handler. This allows apps to react to push messages being received, for example by displaying a notification (using {{domxref("ServiceWorkerRegistration.showNotification()")}}.)

+ +

Each subscription is unique to a service worker.  The endpoint for the subscription is a unique capability URL: knowledge of the endpoint is all that is necessary to send a message to your application. The endpoint URL therefore needs to be kept secret, or other applications might be able to send push messages to your application.

+ +

Activating a service worker to deliver a push message can result in increased resource usage, particularly of the battery. Different browsers have different schemes for handling this — there is currently no standard mechanism. Firefox allows a limited number (quota) of push messages to be sent to an application, although Push messages that generate notifications are exempt from this limit. The limit is refreshed each time the site is visited. In comparison, Chrome applies no limit but requires that every push message causes a notification to be displayed.

+ +
+

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 notifications is received, and not all generate a visible notification.

+
+ +
+

Note: Chrome currently requires 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. This restriction will hopefully be removed in the future.

+
+ +

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 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, and  to 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.)
+
+ +

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]{{CompatNo}}[2]{{CompatUnknown}}{{CompatUnknown}}
{{domxref("PushEvent.data")}},
+ {{domxref("PushMessageData")}}
{{CompatNo}}{{CompatGeckoDesktop(44.0)}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatUnknown}}[2]{{CompatUnknown}}{{CompatUnknown}}{{CompatChrome(42.0)}}
{{domxref("PushEvent.data")}},
+ {{domxref("PushMessageData")}}
{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

[1] Currently available only on desktop versions of Firefox; also, push messages are only delivered when Firefox is running.

+ +

[2] This is currently not implemented. See the Microsoft Edge status information.

+ +

See also

+ + diff --git a/files/id/web/api/cachestorage/index.html b/files/id/web/api/cachestorage/index.html new file mode 100644 index 0000000000..fdcfe56217 --- /dev/null +++ b/files/id/web/api/cachestorage/index.html @@ -0,0 +1,198 @@ +--- +title: CacheStorage +slug: Web/API/CacheStorage +tags: + - API + - CacheStorage + - Experimental + - Interface + - NeedsTranslation + - Reference + - Service Workers + - ServiceWorker + - TopicStub +translation_of: Web/API/CacheStorage +--- +

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

+ +

The CacheStorage interface represents the storage for {{domxref("Cache")}} objects.

+ +

The interface:

+ + + +

Use {{domxref("CacheStorage.open()")}} to obtain a {{domxref("Cache")}} instance.

+ +

Use {{domxref("CacheStorage.match()")}} to check if a given {{domxref("Request")}} is a key in any of the {{domxref("Cache")}} objects that the CacheStorage object tracks.

+ +

You can access CacheStorage through the global {{domxref("WindowOrWorkerGlobalScope.caches", "caches")}} property.

+ +
Note: CacheStorage always rejects with a SecurityError on untrusted origins (i.e. those that aren't using HTTPS, although this definition will likely become more complex in the future.) When testing, you can get around this by checking the "Enable Service Workers over HTTP (when toolbox is open)" option in the Firefox Devtools options/gear menu.
+ +
Note: {{domxref("CacheStorage.match()")}} is a convenience method. Equivalent functionality to match a cache entry can be implemented by returning an array of cache names from {{domxref("CacheStorage.keys()")}}, opening each cache with {{domxref("CacheStorage.open()")}}, and matching the one you want with {{domxref("Cache.match()")}}.
+ +

Methods

+ +
+
{{domxref("CacheStorage.match()")}}
+
Checks if a given {{domxref("Request")}} is a key in any of the {{domxref("Cache")}} objects that the {{domxref("CacheStorage")}} object tracks, and returns a {{jsxref("Promise")}} that resolves to that match.
+
{{domxref("CacheStorage.has()")}}
+
Returns a {{jsxref("Promise")}} that resolves to true if a {{domxref("Cache")}} object matching the cacheName exists.
+
{{domxref("CacheStorage.open()")}}
+
Returns a {{jsxref("Promise")}} that resolves to the {{domxref("Cache")}} object matching the cacheName (a new cache is created if it doesn't already exist.)
+
{{domxref("CacheStorage.delete()")}}
+
Finds the {{domxref("Cache")}} object matching the cacheName, and if found, deletes the {{domxref("Cache")}} object and returns a {{jsxref("Promise")}} that resolves to true. If no {{domxref("Cache")}} object is found, it resolves to false.
+
{{domxref("CacheStorage.keys()")}}
+
Returns a {{jsxref("Promise")}} that will resolve with an array containing strings corresponding to all of the named {{domxref("Cache")}} objects tracked by the {{domxref("CacheStorage")}}. Use this method to iterate over a list of all the {{domxref("Cache")}} objects.
+
+ +

Examples

+ +

This code snippet is from the MDN sw-test example (see sw-test running live.) This service worker script waits for an {{domxref("InstallEvent")}} to fire, then runs {{domxref("ExtendableEvent.waitUntil","waitUntil")}} to handle the install process for the app. This consists of calling {{domxref("CacheStorage.open")}} to create a new cache, then using {{domxref("Cache.addAll")}} to add a series of assets to it.

+ +

In the second code block, we wait for a {{domxref("FetchEvent")}} to fire. We construct a custom response like so:

+ +
    +
  1. Check whether a match for the request is found in the CacheStorage. If so, serve that.
  2. +
  3. If not, fetch the request from the network, then also open the cache created in the first block and add a clone of the request to it using {{domxref("Cache.put")}} (cache.put(event.request, response.clone()).)
  4. +
  5. If this fails (e.g. because the network is down), return a fallback response.
  6. +
+ +

Finally, return whatever the custom response ended up being equal to, using {{domxref("FetchEvent.respondWith")}}.

+ +
self.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/bountyHunters.jpg',
+        '/sw-test/gallery/myLittleVader.jpg',
+        '/sw-test/gallery/snowTroopers.jpg'
+      ]);
+    })
+  );
+});
+
+self.addEventListener('fetch', function(event) {
+  event.respondWith(caches.match(event.request).then(function(response) {
+    // caches.match() always resolves
+    // but in case of success response will have value
+    if (response !== undefined) {
+      return response;
+    } else {
+      return fetch(event.request).then(function (response) {
+        // response may be used only once
+        // we need to save clone to put one copy in cache
+        // and serve second one
+        let responseClone = response.clone();
+
+        caches.open('v1').then(function (cache) {
+          cache.put(event.request, responseClone);
+        });
+        return response;
+      }).catch(function () {
+        return caches.match('/sw-test/gallery/myLittleVader.jpg');
+      });
+    }
+  }));
+});
+
+ +

This snippet shows how the API can be used outside of a service worker context, and uses the await operator for much more readable code.

+ +
// Try to get data from the cache, but fall back to fetching it live.
+async function getData() {
+   const cacheVersion = 1;
+   const cacheName    = `myapp-${ cacheVersion }`;
+   const url          = 'https://jsonplaceholder.typicode.com/todos/1';
+   let cachedData     = await getCachedData( cacheName, url );
+
+   if ( cachedData ) {
+      console.log( 'Retrieved cached data' );
+      return cachedData;
+   }
+
+   console.log( 'Fetching fresh data' );
+
+   const cacheStorage = await caches.open( cacheName );
+   await cacheStorage.add( url );
+   cachedData = await getCachedData( cacheName, url );
+   await deleteOldCaches( cacheName );
+
+   return cachedData;
+}
+
+// Get data from the cache.
+async function getCachedData( cacheName, url ) {
+   const cacheStorage   = await caches.open( cacheName );
+   const cachedResponse = await cacheStorage.match( url );
+
+   if ( ! cachedResponse || ! cachedResponse.ok ) {
+      return false;
+   }
+
+   return await cachedResponse.json();
+}
+
+// Delete any old caches to respect user's disk space.
+async function deleteOldCaches( currentCache ) {
+   const keys = await caches.keys();
+
+   for ( const key of keys ) {
+      const isOurCache = 'myapp-' === key.substr( 0, 6 );
+
+      if ( currentCache === key || ! isOurCache ) {
+         continue;
+      }
+
+      caches.delete( key );
+   }
+}
+
+try {
+   const data = await getData();
+   console.log( { data } );
+} catch ( error ) {
+   console.error( { error } );
+}
+ +

Specifications

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

Browser compatibility

+ + + +

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

+ +

See also

+ + diff --git a/files/id/web/api/canvas_api/index.html b/files/id/web/api/canvas_api/index.html new file mode 100644 index 0000000000..0cdd4219fe --- /dev/null +++ b/files/id/web/api/canvas_api/index.html @@ -0,0 +1,172 @@ +--- +title: Canvas API +slug: Web/API/Canvas_API +tags: + - API + - Canvas + - Gambar + - JavaScript + - Referensi +translation_of: Web/API/Canvas_API +--- +
{{CanvasSidebar}}
+ +

Ditambahkan di HTML5, elemen HTML {{HTMLElement("canvas")}} dapat digunakan untuk menggambar grafik melalui skrip di JavaScript. Sebagai contoh, dapat digunakan untuk menggambar graf, membuat komposisi foto, mencipta animasi, atau bahkan melakukan pemrosesan atau rendering video secara waktu-nyata .

+ +

Aplikasi Mozilla mendapat dukungan untuk <canvas> sejak Gecko 1.8 (i.e. Firefox 1.5). Elemen tersebut semula dikenalkan oleh Apple untuk Dashboard OS X dan Safari. Internet Explorer mendukung <canvas> sejak versi 9 dan seterusnya; untuk versi awal IE, sebuah halaman dapat secara efektif mendukung <canvas> dengan memasukkan skrip dari proyek Explorer Canvas Google. Google Chrome dan Opera 9 juga mendukung <canvas>.

+ +

Elemen <canvas> juga digunakan oleh WebGL untuk menggambar grafik hardware-accelerated 3D di halaman web.

+ +

Contoh

+ +

Ini hanya cuplikan kode sederhana yang menggunakan metode  {{domxref("CanvasRenderingContext2D.fillRect()")}}.

+ +

HTML

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

JavaScript

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

Edit kode di bawah dan lihat perbaruan perubahannya di kanvas secara waktu-nyata:

+ + + +

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

+ +

Reference

+ +
+ +
+ +

The interfaces related to the WebGLRenderingContext are referenced under WebGL.

+ +

{{domxref("CanvasCaptureMediaStream")}} is related.

+ +

Petunjuk dan tutorial

+ +
+
Tutorial canvas
+
Tutorial komprehensif mengcakup penggunaan sederhana  <canvas> dan fitur lanjutannya.
+
Cuplikan kode: Canvas
+
Beberapa cuplikan kode pengembang berorientasi ekstensi yang melibatkan <canvas>.
+
Demo: ray-caster sederhana
+
Demo animasi ray-tracing menggunakan canvas.
+
Menggambar DOM objects ke canvas
+
Bagaimana menggambar konten DOM, seperti elemen HTML, pada canvas.
+
Memanipulasi video dengan canvas
+
Menggabungkan {{HTMLElement("video")}} dan {{HTMLElement("canvas")}} untuk memanipulasi data video secara real time.
+
+ +

Sumber

+ +

Generik

+ + + +

Librari

+ + + +

Spesifikasi

+ + + + + + + + + + + + + + + + +
SpesifikasiStatusKomentar
{{SpecName('HTML WHATWG', 'scripting.html#the-canvas-element', '<canvas>')}}{{Spec2('HTML WHATWG')}}
+ +

Lihat juga

+ + diff --git a/files/id/web/api/console/index.html b/files/id/web/api/console/index.html new file mode 100644 index 0000000000..05cdba529b --- /dev/null +++ b/files/id/web/api/console/index.html @@ -0,0 +1,278 @@ +--- +title: Console +slug: Web/API/Console +tags: + - API + - Debugging + - Interface + - NeedsCompatTable + - NeedsTranslation + - Reference + - TopicStub + - console + - web console +translation_of: Web/API/Console +--- +
{{APIRef("Console API")}}
+ +

The Console object provides access to the browser's debugging console (e.g., the Web Console in Firefox). The specifics of how it works vary from browser to browser, but there is a de facto set of features that are typically provided.

+ +

The Console object can be accessed from any global object, {{domxref("Window")}} on browsing scopes, {{domxref("WorkerGlobalScope")}}, and its specific variants in workers via property console. It's exposed as {{domxref("Window.console")}}, and can be referenced as simply console. For example:

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

This page documents the {{anch("Methods")}} available on the Console object and gives a few {{anch("Usage")}} examples.

+ +

{{AvailableInWorkers}}

+ +

Methods

+ +
+
{{domxref("Console.assert()")}}
+
Log a message and stack trace to console if first argument is false.
+
{{domxref("Console.clear()")}}
+
Clear the console.
+
{{domxref("Console.count()")}}
+
Log the number of times this line has been called with the given label.
+
{{domxref("Console.debug()")}}
+
An alias for log() - starting with Chromium 58 this method is a no-op on Chromium browsers.
+
{{domxref("Console.dir()")}} {{Non-standard_inline}}
+
Displays an interactive listing of the properties of a specified JavaScript object. This listing lets you use disclosure triangles to examine the contents of child objects.
+
{{domxref("Console.dirxml()")}} {{Non-standard_inline}}
+
+

Displays an XML/HTML Element representation of the specified object if possible or the JavaScript Object view if it is not.

+
+
{{domxref("Console.error()")}}
+
Outputs an error message. You may use string substitution and additional arguments with this method.
+
{{domxref("Console.exception()")}} {{Non-standard_inline}} {{deprecated_inline}}
+
An alias for error()
+
{{domxref("Console.group()")}}
+
Creates a new inline group, indenting all following output by another level. To move back out a level, call groupEnd().
+
{{domxref("Console.groupCollapsed()")}}
+
Creates a new inline group, indenting all following output by another level; unlike group(), this starts with the inline group collapsed, requiring the use of a disclosure button to expand it. To move back out a level, call groupEnd().
+
{{domxref("Console.groupEnd()")}}
+
Exits the current inline group.
+
{{domxref("Console.info()")}}
+
Informative logging information. You may use string substitution and additional arguments with this method.
+
{{domxref("Console.log()")}}
+
For general output of logging information. You may use string substitution and additional arguments with this method.
+
{{domxref("Console.profile()")}} {{Non-standard_inline}}
+
Starts the browser's build-in profiler (for example, the Firefox performance tool). You can specify an optional name for the profile.
+
{{domxref("Console.profileEnd()")}} {{Non-standard_inline}}
+
Stops the profiler. You can see the resulting profile in the browser's performance tool (for example, the Firefox performance tool).
+
{{domxref("Console.table()")}}
+
Displays tabular data as a table.
+
{{domxref("Console.time()")}}
+
Starts a timer with a name specified as an input parameter. Up to 10,000 simultaneous timers can run on a given page.
+
{{domxref("Console.timeEnd()")}}
+
Stops the specified timer and logs the elapsed time in seconds since its start.
+
{{domxref("Console.timeStamp()")}} {{Non-standard_inline}}
+
Adds a marker to the browser's Timeline or Waterfall tool.
+
{{domxref("Console.trace()")}}
+
Outputs a stack trace.
+
{{domxref("Console.warn()")}}
+
Outputs a warning message. You may use string substitution and additional arguments with this method.
+
+ + +

Usage

+ +

Outputting text to the console

+ +

The most frequently-used feature of the console is logging of text and other data. There are four categories of output you can generate, using the {{domxref("console.log()")}}, {{domxref("console.info()")}}, {{domxref("console.warn()")}}, and {{domxref("console.error()")}} methods. Each of these results in output that's styled differently in the log, and you can use the filtering controls provided by your browser to only view the kinds of output that interest you.

+ +

There are two ways to use each of the output methods; you can simply pass in a list of objects whose string representations get concatenated into one string, then output to the console, or you can pass in a string containing zero or more substitution strings followed by a list of the objects with which to replace them.

+ +

Outputting a single object

+ +

The simplest way to use the logging methods is to output a single object:

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

The output looks something like this:

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

Outputting multiple objects

+ +

You can also output multiple objects by simply listing them when calling the logging method, like this:

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

This output will look like this:

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

Using string substitutions

+ +

Gecko 9.0 {{geckoRelease("9.0")}} introduced support for string substitutions. When passing a string to one of the console object's methods that accepts a string, you may use these substitution strings:

+ + + + + + + + + + + + + + + + + + + + + + + + +
Substitution stringDescription
%o or %OOutputs a JavaScript object. Clicking the object name opens more information about it in the inspector.
%d or %iOutputs an integer. Number formatting is supported, for example  console.log("Foo %.2d", 1.1) will output the number as two significant figures with a leading 0: Foo 01
%sOutputs a string.
%fOutputs a floating-point value. Formatting is supported, for example  console.log("Foo %.2f", 1.1) will output the number to 2 decimal places: Foo 1.10
+ +

Each of these pulls the next argument after the format string off the parameter list. For example:

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

The output looks like this:

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

Styling console output

+ +

You can use the "%c" directive to apply a CSS style to console output:

+ +
console.log("This is %cMy stylish message", "color: yellow; font-style: italic; background-color: blue;padding: 2px");
+ +
The text before the directive will not be affected, but the text after the directive will be styled using the CSS declarations in the parameter.
+ +
 
+ +
+ +
 
+ +
+

Note: Quite a few CSS properties are supported by this styling; you should experiment and see which ones prove useful.

+
+ +
 
+ +
{{h3_gecko_minversion("Using groups in the console", "9.0")}}
+ +

You can use nested groups to help organize your output by visually combining related material. To create a new nested block, call console.group(). The console.groupCollapsed() method is similar, but creates the new block collapsed, requiring the use of a disclosure button to open it for reading.

+ +
Note: Collapsed groups are not supported yet in Gecko; the groupCollapsed() method is the same as group() at this time.
+ +

To exit the current group, simply call console.groupEnd(). For example, given this code:

+ +
console.log("This is the outer level");
+console.group();
+console.log("Level 2");
+console.group();
+console.log("Level 3");
+console.warn("More of level 3");
+console.groupEnd();
+console.log("Back to level 2");
+console.groupEnd();
+console.debug("Back to the outer level");
+
+ +

The output looks like this:

+ +

nesting.png

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

In order to calculate the duration of a specific operation, Gecko 10 introduced the support of timers in the console object. To start a timer, call the console.time() method, giving it a name as the only parameter. To stop the timer, and to get the elapsed time in milliseconds, just call the console.timeEnd() method, again passing the timer's name as the parameter. Up to 10,000 timers can run simultaneously on a given page.

+ +

For example, given this code:

+ +
console.time("answer time");
+alert("Click to continue");
+console.timeEnd("answer time");
+
+ +

will log the time needed by the user to discard the alert box:

+ +

timerresult.png

+ +

Notice that the timer's name is displayed both when the timer is started and when it's stopped.

+ +
Note: It's important to note that if you're using this to log the timing for network traffic, the timer will report the total time for the transaction, while the time listed in the network panel is just the amount of time required for the header. If you have response body logging enabled, the time listed for the response header and body combined should match what you see in the console output.
+ +

Stack traces

+ +

The console object also supports outputting a stack trace; this will show you the call path taken to reach the point at which you call {{domxref("console.trace()")}}. Given code like this:

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

The output in the console looks something like this:

+ +

+ +

Specifications

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

Notes

+ + + +

See also

+ + + +

Other implementations

+ + diff --git a/files/id/web/api/document/createelement/index.html b/files/id/web/api/document/createelement/index.html new file mode 100644 index 0000000000..0f14c4e8ce --- /dev/null +++ b/files/id/web/api/document/createelement/index.html @@ -0,0 +1,225 @@ +--- +title: Document.createElement() +slug: Web/API/Document/createElement +tags: + - API + - DOM + - Document + - Metode + - Referensi + - createElement +translation_of: Web/API/Document/createElement +--- +
{{APIRef("DOM")}}
+ +

Dalam sebuah dokumen HTML, metode document.createElement() membuat elemen HTML yang ditentukan oleh tagName, atau sebuah  {{domxref("HTMLUnknownElement")}} jika tagName tidak dikenali.

+ +
+

Catatan: Dalam sebuah dokumen XUL , ini membuat elemen XUL yang ditentukan. Pada dokumen lain, ini membuat sebuah elemen dengan sebuah namespace URI yang null.

+
+ +

Sintaks

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

Parameter

+ +
+
tagName
+
Sebuah string yang menentukan tipe dari elemen yang akan dibuat. {{domxref("Node.nodeName", "nodeName")}} dari elemen dibuat dengan nilai tagName. Jangan menggunakan nama yang memenuhi syarat (seperti "html:a") dengan metode ini. Ketika dipanggil pada sebuah dokumen HTML, createElement() mengubah tagName menjadi lower case sebelum membuat elemen. Pada Firefox, Opera, dan Chrome, createElement(null) bekerja seperti createElement("null").
+
options{{optional_inline}}
+
Sebuah objek opsional ElementCreationOptions berisi sebuah properti tunggal bernama is, yang nilainya adalah nama tag untuk sebuah elemen khusus yang sebelumnya didefinisikan menggunakan customElements.define(). Lihat {{anch("Web component example")}} untuk lebih jelasnya.
+
+ +

Return value

+ +

Element baru.

+ +

Contoh

+ +

Contoh dasar

+ +

Ini membuat sebuah <div> baru dan memasukannya sebelum elemen dengan ID "div1".

+ +

HTML

+ +
<!DOCTYPE html>
+<html>
+<head>
+  <title>||Bekerja dengan elemen||</title>
+</head>
+<body>
+  <div id="div1">Teks di atas telah dibuat secara dinamis.</div>
+</body>
+</html>
+
+ +

JavaScript

+ +
document.body.onload = addElement;
+
+function addElement () {
+  // membuat sebuah elemen div baru
+  var newDiv = document.createElement("div");
+  // dan memberikannya sebuah konten
+  var newContent = document.createTextNode("Hi there and greetings!");
+  // menambahkan teks terebut ke div yang baru dibuat
+  newDiv.appendChild(newContent);
+
+  // menambah elemen yang baru dibuat berserta isinya ke dalam DOM
+  var currentDiv = document.getElementById("div1");
+  document.body.insertBefore(newDiv, currentDiv);
+}
+ +

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

+ +

Contoh komponen web

+ +

Contoh cuplikan berikut diambil dari contoh dari expanding-list-web-component kami (lihat juga secara langsung). Dalam kasus ini, elemen khusus kami memperluas {{domxref("HTMLUListElement")}}, yang mewakili elemen {{htmlelement("ul")}}.

+ +
// Membuat sebuah kelas untuk elemen
+class ExpandingList extends HTMLUListElement {
+  constructor() {
+    // Selalu memanggil super dulu di konstruktor
+    super();
+
+    // definisi konstruktor dihilangkan untuk singkatnya
+    ...
+  }
+}
+
+// Mendefinisi elemen baru
+customElements.define('expanding-list', ExpandingList, { extends: "ul" });
+ +

Jika kita ingin untuk membuat sebuah instance dari elemen ini secara terprogram, kita akan menggunakan sebuah panggilan di sepanjang baris berikut:

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

Elemen baru akan diberikan sebuah atribut is yang nilainya adalah nama tag elemen khusus.

+ +
+

Catatan: Untuk kompabilitas ke belakang untuk versi sebelumnya dari Spesifikasi Elemen khusus, beberapa peramban (browser) akan memungkinkan Anda untuk melewatkan sebuah string di sini bukan pada sebuah objek, yang mana nilai string  adalah nama tag elemen khusus.

+
+ +

Spesifikasi

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

Kompabilitas peramban

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FiturChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Dukungan dasar{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}[1][2]{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
argumen options{{CompatVersionUnknown}}[3]{{CompatUnknown}}{{CompatGeckoDesktop(50)}}[4][5]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FiturAndroidAndroid WebviewEdgeFirefox Mobile (Gecko)IE PhoneOpera MobileSafari MobileChrome for Android
Dukungan dasar{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
argumen options{{CompatVersionUnknown}}{{CompatVersionUnknown}}[3]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}[3]
+
+ +

[1] Dimulai dengan Gecko 22.0 {{geckoRelease("22.0")}} createElement() tidak lagi menggunakan antarmuka {{domxref("HTMLSpanElement")}} ketika argumennya adalah "bgsounds", "multicol", atau "image".  Sebagai gantinya, HTMLUnknownElement digunakan untuk "bgsound" dan "multicol" dan {{domxref("HTMLElement")}} HTMLElement digunakan untuk "image".

+ +

[2] Implementasi Gecko dari createElement tidak sesuai dengan spesifikasi DOM untuk dokumen XUL dan XHTML: localName dan namespaceURI tidak diatur ke null pada elemen yang dibuat. Lihat {{ Bug(280692) }} untuk lebih jelasnya.

+ +

[3] Pada versi sebelumnya dari spesifikasi, argumen ini hanyalah sebuah string yang nilainyaadalah nama tag elemen khusus. Misalnya bisa saja document.createElement("button", "custom-button") daripada document.createElement("button", {is: "custom-button"}). Demi kompabilitas ke belakang, Chrome menerima kedua bentuk tersebut, meskipun bentuk string sudah usang.

+ +

[4] Liat [3] di atas: seperti Chrome, Firefox menerima string, bukan sebuah objek di sini, tetapi hanya dari versi 51 dan seterusnya. Pada versi 50, options harus sebuah objek.

+ +

[5] Untuk eksperimen dengan elemen khusus di Firefox, Anda harus mengatur preferensi dom.webcomponents.enabled dan dom.webcomponents.customelements.enabled menjadi true.

+ +

Catatan Quantum CSS

+ + + +

Lihat juga

+ + diff --git a/files/id/web/api/document/index.html b/files/id/web/api/document/index.html new file mode 100644 index 0000000000..08e82db4cc --- /dev/null +++ b/files/id/web/api/document/index.html @@ -0,0 +1,576 @@ +--- +title: Document +slug: Web/API/Document +tags: + - API + - DOM + - Interface + - NeedsTranslation + - Reference + - TopicStub +translation_of: Web/API/Document +--- +
{{APIRef}}
+ +
 
+ +

The Document interface represents any web page loaded in the browser and serves as an entry point into the web page's content, which is the DOM tree. The DOM tree includes elements such as {{HTMLElement("body")}} and {{HTMLElement("table")}}, among many others. It provides functionality which is global to the document, such as obtaining the page's URL and creating new elements in the document.

+ +

{{inheritanceDiagram}}

+ +

The Document interface describes the common properties and methods for any kind of document. Depending on the document's type (e.g. HTML, XML, SVG, …), a larger API is available: HTML documents, served with the text/html content type, also implement the {{domxref("HTMLDocument")}} interface, wherease SVG documents implement the {{domxref("SVGDocument")}} interface.

+ +

Properties

+ +

This interface also inherits from the {{domxref("Node")}} and {{domxref("EventTarget")}} interfaces.

+ +
+
{{domxref("Document.all")}} {{Deprecated_inline}} {{non-standard_inline}}
+
Provides access to all elements with an id. This is a legacy, non-standard interface and 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")}} {{readonlyinline}}
+
Returns the character set being used by the document.
+
{{domxref("Document.charset")}} {{readonlyinline}} {{Deprecated_inline}}
+
Alias of {{domxref("Document.characterSet")}}. Use this property instead.
+
{{domxref("Document.compatMode")}} {{readonlyinline}} {{experimental_inline}}
+
Indicates whether the document is rendered in quirks or strict mode.
+
{{domxref("Document.contentType")}} {{readonlyinline}} {{experimental_inline}}
+
Returns the Content-Type from the MIME Header of the current document.
+
{{domxref("Document.doctype")}} {{readonlyinline}}
+
Returns the Document Type Definition (DTD) of the current document.
+
{{domxref("Document.documentElement")}} {{readonlyinline}}
+
Returns the {{domxref("Element")}} that is a direct child of the document. For HTML documents, this is normally the HTML element.
+
{{domxref("Document.documentURI")}} {{readonlyinline}}
+
Returns the document location as a string.
+
{{domxref("Document.domConfig")}} {{Deprecated_inline}}
+
Should return a {{domxref("DOMConfiguration")}} object.
+
{{domxref("Document.fullscreen")}} {{obsolete_inline}}
+
true when the document is in {{domxref("Using_full-screen_mode","full-screen mode")}}.
+
{{domxref("Document.hidden")}} {{readonlyinline}}
+
+
{{domxref("Document.implementation")}} {{readonlyinline}}
+
Returns the DOM implementation associated with the current document.
+
{{domxref("Document.inputEncoding")}} {{readonlyinline}} {{Deprecated_inline}}
+
Alias of {{domxref("Document.characterSet")}}. Use this property instead.
+
{{domxref("Document.lastStyleSheetSet")}} {{readonlyinline}}
+
Returns the name of the style sheet set that was last enabled. Has the value null until the style sheet is changed by setting the value of {{domxref("document.selectedStyleSheetSet","selectedStyleSheetSet")}}.
+
{{domxref("Document.mozSyntheticDocument")}} {{non-standard_inline}} {{gecko_minversion_inline("8.0")}}
+
Returns a {{jsxref("Boolean")}} that is true only if this document is synthetic, such as a standalone image, video, audio file, or the like.
+
{{domxref("Document.mozFullScreenElement")}} {{readonlyinline}} {{non-standard_inline}} {{gecko_minversion_inline("9.0")}}
+
The element that's currently in full screen mode for this document.
+
{{domxref("Document.mozFullScreenEnabled")}} {{readonlyinline}} {{non-standard_inline}} {{gecko_minversion_inline("9.0")}}
+
true if calling {{domxref("Element.mozRequestFullscreen()")}} would succeed in the curent document.
+
{{domxref("Document.pointerLockElement")}} {{readonlyinline}} {{experimental_inline}}
+
Returns the element set as the target for mouse events while the pointer is locked. null if lock is pending, pointer is unlocked, or if the target is in another document.
+
{{domxref("Document.preferredStyleSheetSet")}} {{readonlyinline}}
+
Returns the preferred style sheet set as specified by the page author.
+
{{domxref("Document.scrollingElement")}} {{experimental_inline}} {{readonlyinline}}
+
Returns a reference to the {{domxref("Element")}} that scrolls the document.
+
{{domxref("Document.selectedStyleSheetSet")}}
+
Returns which style sheet set is currently in use.
+
{{domxref("Document.styleSheets")}} {{readonlyinline}}
+
Returns a list of the style sheet objects on the current document.
+
{{domxref("Document.styleSheetSets")}} {{readonlyinline}}
+
Returns a list of the style sheet sets available on the document.
+
{{domxref("Document.timeline")}} {{readonlyinline}}
+
+
{{domxref("Document.undoManager")}} {{readonlyinline}} {{experimental_inline}}
+
+
{{domxref("Document.URL")}} {{readonlyinline}}
+
Returns ...
+
{{domxref("Document.visibilityState")}} {{readonlyinline}}
+
+
{{domxref("Document.xmlEncoding")}} {{Deprecated_inline}}
+
Returns the encoding as determined by the XML declaration.
+
{{domxref("Document.xmlStandalone")}} {{obsolete_inline("10.0")}}
+
Returns true if the XML declaration specifies the document to be standalone (e.g., An external part of the DTD affects the document's content), else false.
+
{{domxref("Document.xmlVersion")}} {{obsolete_inline("10.0")}}
+
Returns the version number as specified in the XML declaration or "1.0" if the declaration is absent.
+
+ +

The Document interface is extended with the {{domxref("ParentNode")}} interface:

+ +

{{page("/en-US/docs/Web/API/ParentNode","Properties")}}

+ +

Extension for HTML document

+ +

The Document interface for HTML documents inherits from the {{domxref("HTMLDocument")}} interface or, since HTML5,  is extended for such documents.

+ +
+
{{domxref("Document.activeElement")}} {{readonlyinline}}
+
Returns the currently focused element.
+
{{domxref("Document.alinkColor")}} {{Deprecated_inline}}
+
Returns or sets the color of active links in the document body.
+
{{domxref("Document.anchors")}}
+
Returns a list of all of the anchors in the document.
+
{{domxref("Document.applets")}} {{Deprecated_inline}}
+
Returns an ordered list of the applets within a document.
+
{{domxref("Document.bgColor")}} {{Deprecated_inline}}
+
Gets/sets the background color of the current document.
+
{{domxref("Document.body")}}
+
Returns the {{HTMLElement("body")}} element of the current document.
+
{{domxref("Document.cookie")}}
+
Returns a semicolon-separated list of the cookies for that document or sets a single cookie.
+
{{domxref("Document.defaultView")}} {{readonlyinline}}
+
Returns a reference to the window object.
+
{{domxref("Document.designMode")}}
+
Gets/sets the ability to edit the whole document.
+
{{domxref("Document.dir")}} {{readonlyinline}}
+
Gets/sets directionality (rtl/ltr) of the document.
+
{{domxref("Document.domain")}} {{readonlyinline}}
+
Returns the domain of the current document.
+
{{domxref("Document.embeds")}} {{readonlyinline}}
+
Returns a list of the embedded {{HTMLElement('embed')}} elements within the current document.
+
{{domxref("document.fgColor")}} {{Deprecated_inline}}
+
Gets/sets the foreground color, or text color, of the current document.
+
{{domxref("Document.forms")}} {{readonlyinline}}
+
Returns a list of the {{HTMLElement("form")}} elements within the current document.
+
{{domxref("Document.head")}} {{readonlyinline}}
+
Returns the {{HTMLElement("head")}} element of the current document.
+
{{domxref("Document.height")}} {{non-standard_inline}} {{obsolete_inline}}
+
Gets/sets the height of the current document.
+
{{domxref("Document.images")}} {{readonlyinline}}
+
Returns a list of the images in the current document.
+
{{domxref("Document.lastModified")}} {{readonlyinline}}
+
Returns the date on which the document was last modified.
+
{{domxref("Document.linkColor")}} {{Deprecated_inline}}
+
Gets/sets the color of hyperlinks in the document.
+
{{domxref("Document.links")}} {{readonlyinline}}
+
Returns a list of all the hyperlinks in the document.
+
{{domxref("Document.location")}} {{readonlyinline}}
+
Returns the URI of the current document.
+
{{domxref("Document.plugins")}} {{readonlyinline}}
+
Returns a list of the available plugins.
+
{{domxref("Document.readyState")}} {{readonlyinline}}  {{gecko_minversion_inline("1.9.2")}}
+
Returns loading status of the document.
+
{{domxref("Document.referrer")}} {{readonlyinline}}
+
Returns the URI of the page that linked to this page.
+
{{domxref("Document.scripts")}} {{readonlyinline}}
+
Returns all the {{HTMLElement("script")}} elements on the document.
+
{{domxref("Document.title")}}
+
Sets or gets title of the current document.
+
{{domxref("Document.URL")}} {{readonlyInline}}
+
Returns the document location as a string.
+
{{domxref("Document.vlinkColor")}} {{Deprecated_inline}}
+
Gets/sets the color of visited hyperlinks.
+
{{domxref("Document.width")}} {{non-standard_inline}} {{obsolete_inline}}
+
Returns the width of the current document.
+
+ +

Event handlers

+ +
+
{{domxref("GlobalEventHandlers.onabort")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("abort")}} event is raised.
+
{{domxref("Document.onafterscriptexecute")}} {{non-standard_inline}}
+
Represents the event handling code for the {{event("afterscriptexecute")}} event.
+
{{domxref("Document.onbeforescriptexecute")}} {{non-standard_inline}}
+
Represents the event handling code for the {{event("beforescriptexecute")}} event.
+
{{domxref("GlobalEventHandlers.onblur")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("blur")}} event is raised.
+
{{domxref("GlobalEventHandlers.oncancel")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("cancel")}} event is raised.
+
{{domxref("GlobalEventHandlers.oncanplay")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("canplay")}} event is raised.
+
{{domxref("GlobalEventHandlers.oncanplaythrough")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("canplaythrough")}} event is raised.
+
{{domxref("GlobalEventHandlers.onchange")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("change")}} event is raised.
+
{{domxref("GlobalEventHandlers.onclick")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("click")}} event is raised.
+
{{domxref("GlobalEventHandlers.onclose")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("close")}} event is raised.
+
{{domxref("GlobalEventHandlers.oncontextmenu")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("contextmenu")}} event is raised.
+
{{domxref("Document.oncopy")}} {{non-standard_inline}}
+
Represents the event handling code for the {{event("copy")}} event.
+
{{domxref("GlobalEventHandlers.oncuechange")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("cuechange")}} event is raised.
+
{{domxref("Document.oncut")}} {{non-standard_inline}}
+
Represents the event handling code for the {{event("cut")}} event.
+
{{domxref("GlobalEventHandlers.ondblclick")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("dblclick")}} event is raised.
+
{{domxref("GlobalEventHandlers.ondrag")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("drag")}} event is raised.
+
{{domxref("GlobalEventHandlers.ondragend")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("dragend")}} event is raised.
+
{{domxref("GlobalEventHandlers.ondragenter")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("dragenter")}} event is raised.
+
{{domxref("GlobalEventHandlers.ondragexit")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("dragexit")}} event is raised.
+
{{domxref("GlobalEventHandlers.ondragleave")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("dragleave")}} event is raised.
+
{{domxref("GlobalEventHandlers.ondragover")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("dragover")}} event is raised.
+
{{domxref("GlobalEventHandlers.ondragstart")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("dragstart")}} event is raised.
+
{{domxref("GlobalEventHandlers.ondrop")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("drop")}} event is raised.
+
{{domxref("GlobalEventHandlers.ondurationchange")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("durationchange")}} event is raised.
+
{{domxref("GlobalEventHandlers.onemptied")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("emptied")}} event is raised.
+
{{domxref("GlobalEventHandlers.onended")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("ended")}} event is raised.
+
{{domxref("GlobalEventHandlers.onerror")}}
+
Is an {{domxref("OnErrorEventHandler")}} representing the code to be called when the {{event("error")}} event is raised.
+
{{domxref("GlobalEventHandlers.onfocus")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("focus")}} event is raised.
+
{{domxref("Document.onfullscreenchange")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("fullscreenchange")}} event is raised.
+
{{domxref("Document.onfullscreenerror")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("fullscreenerror")}} event is raised.
+
{{domxref("GlobalEventHandlers.oninput")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("input")}} event is raised.
+
{{domxref("GlobalEventHandlers.oninvalid")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("invalid")}} event is raised.
+
{{domxref("GlobalEventHandlers.onkeydown")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("keydown")}} event is raised.
+
{{domxref("GlobalEventHandlers.onkeypress")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("keypress")}} event is raised.
+
{{domxref("GlobalEventHandlers.onkeyup")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("keyup")}} event is raised.
+
{{domxref("GlobalEventHandlers.onload")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("load")}} event is raised.
+
{{domxref("GlobalEventHandlers.onloadeddata")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("loadeddata")}} event is raised.
+
{{domxref("GlobalEventHandlers.onloadedmetadata")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("loadedmetadata")}} event is raised.
+
{{domxref("GlobalEventHandlers.onloadstart")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("loadstart")}} event is raised.
+
{{domxref("GlobalEventHandlers.onmousedown")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("mousedown")}} event is raised.
+
{{domxref("GlobalEventHandlers.onmouseenter")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("mouseenter")}} event is raised.
+
{{domxref("GlobalEventHandlers.onmouseleave")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("mouseleave")}} event is raised.
+
{{domxref("GlobalEventHandlers.onmousemove")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("mousemove")}} event is raised.
+
{{domxref("GlobalEventHandlers.onmouseout")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("mouseout")}} event is raised.
+
{{domxref("GlobalEventHandlers.onmouseover")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("mouseover")}} event is raised.
+
{{domxref("GlobalEventHandlers.onmouseup")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("mouseup")}} event is raised.
+
{{domxref("GlobalEventHandlers.onmousewheel")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("mousewheel")}} event is raised.
+
{{domxref("GlobalEventHandlers.onpause")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("pause")}} event is raised.
+
{{domxref("Document.onpaste")}} {{non-standard_inline}}
+
Represents the event handling code for the {{event("paste")}} event.
+
{{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("Document.onpointerlockchange")}} {{experimental_inline}}
+
Represents the event handling code for the {{event("pointerlockchange")}} event.
+
{{domxref("Document.onpointerlockerror")}} {{experimental_inline}}
+
Represetnts the event handling code for the {{event("pointerlockerror")}} event.
+
{{domxref("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("Document.onreadystatechange")}} {{gecko_minversion_inline("1.9.2")}}
+
Represents the event handling code for the {{event("readystatechange")}} event.
+
{{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.onselectstart")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("selectstart")}} event is raised.
+
{{domxref("Document.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.onwaiting")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("waiting")}} event is raised.
+
{{domxref("Document.onwheel")}} {{non-standard_inline}}
+
Represents the event handling code for the {{event("wheel")}} event.
+
+ +

Methods

+ +

This interface also inherits from the {{domxref("Node")}} and {{domxref("EventTarget")}} interfaces.

+ +
+
{{domxref("Document.adoptNode()")}}
+
Adopt node from an external document.
+
{{domxref("Document.captureEvents()")}} {{Deprecated_inline}}
+
See {{domxref("Window.captureEvents")}}.
+
{{domxref("Document.caretPositionFromPoint()")}}{{experimental_inline}}
+
Gets the {{domxref("CaretPosition")}} at or near the specified coordinates.
+
{{domxref("Document.caretRangeFromPoint()")}}{{non-standard_inline}}
+
Gets a {{Domxref("Range")}} object for the document fragment under the specified coordinates.
+
{{domxref("Document.createAttribute()")}}
+
Creates a new {{domxref("Attr")}} object and returns it.
+
{{domxref("Document.createAttributeNS()")}}
+
Creates a new attribute node in a given namespace and returns it.
+
{{domxref("Document.createCDATASection()")}}
+
Creates a new CDATA node and returns it.
+
{{domxref("Document.createComment()")}}
+
Creates a new comment node and returns it.
+
{{domxref("Document.createDocumentFragment()")}}
+
Creates a new document fragment.
+
{{domxref("Document.createElement()")}}
+
Creates a new element with the given tag name.
+
{{domxref("Document.createElementNS()")}}
+
Creates a new element with the given tag name and namespace URI.
+
{{domxref("Document.createEntityReference()")}} {{obsolete_inline}}
+
Creates a new entity reference object and returns it.
+
{{domxref("Document.createEvent()")}}
+
Creates an event object.
+
{{domxref("Document.createNodeIterator()")}}
+
Creates a {{domxref("NodeIterator")}} object.
+
{{domxref("Document.createProcessingInstruction()")}}
+
Creates a new {{domxref("ProcessingInstruction")}} object.
+
{{domxref("Document.createRange()")}}
+
Creates a {{domxref("Range")}} object.
+
{{domxref("Document.createTextNode()")}}
+
Creates a text node.
+
{{domxref("Document.createTouch()")}}
+
Creates a {{domxref("Touch")}} object.
+
{{domxref("Document.createTouchList()")}}
+
Creates a {{domxref("TouchList")}} object.
+
{{domxref("Document.createTreeWalker()")}}
+
Creates a {{domxref("TreeWalker")}} object.
+
{{domxref("Document.elementFromPoint()")}}{{experimental_inline}}
+
Returns the topmost element at the specified coordinates. 
+
{{domxref("Document.elementsFromPoint()")}}{{experimental_inline}}
+
Returns an array of all elements at the specified coordinates.
+
{{domxref("Document.enableStyleSheetsForSet()")}}
+
Enables the style sheets for the specified style sheet set.
+
{{domxref("Document.exitPointerLock()")}} {{experimental_inline}}
+
Release the pointer lock.
+
{{domxref("Document.getAnimations()")}} {{experimental_inline}}
+
Returns an array of all {{domxref("Animation")}} objects currently in effect whose target elements are descendants of the document.
+
{{domxref("Document.getElementsByClassName()")}}
+
Returns a list of elements with the given class name.
+
{{domxref("Document.getElementsByTagName()")}}
+
Returns a list of elements with the given tag name.
+
{{domxref("Document.getElementsByTagNameNS()")}}
+
Returns a list of elements with the given tag name and namespace.
+
{{domxref("Document.importNode()")}}
+
Returns a clone of a node from an external document.
+
{{domxref("Document.normalizeDocument()")}} {{obsolete_inline}}
+
Replaces entities, normalizes text nodes, etc.
+
{{domxref("Document.registerElement()")}} {{experimental_inline}}
+
Registers a web component.
+
{{domxref("Document.releaseCapture()")}} {{non-standard_inline}} {{gecko_minversion_inline("2.0")}}
+
Releases the current mouse capture if it's on an element in this document.
+
{{domxref("Document.releaseEvents()")}} {{non-standard_inline}} {{Deprecated_inline}}
+
See {{domxref("Window.releaseEvents()")}}.
+
{{domxref("Document.routeEvent()")}} {{non-standard_inline}} {{obsolete_inline(24)}}
+
See {{domxref("Window.routeEvent()")}}.
+
{{domxref("Document.mozSetImageElement()")}} {{non-standard_inline}} {{gecko_minversion_inline("2.0")}}
+
Allows you to change the element being used as the background image for a specified element ID.
+
+ +

The Document interface is extended with the {{domxref("ParentNode")}} interface:

+ +
+
{{domxref("document.getElementById","document.getElementById(String id)")}}
+
Returns an object reference to the identified element.
+
{{domxref("document.querySelector","document.querySelector(String selector)")}} {{gecko_minversion_inline("1.9.1")}}
+
Returns the first Element node within the document, in document order, that matches the specified selectors.
+
{{domxref("document.querySelectorAll","document.querySelectorAll(String selector)")}} {{gecko_minversion_inline("1.9.1")}}
+
Returns a list of all the Element nodes within the document that match the specified selectors.
+
+ +

The Document interface is extended with the {{domxref("XPathEvaluator")}} interface:

+ +
+
{{domxref("document.createExpression","document.createExpression(String expression, XPathNSResolver resolver)")}}
+
Compiles an XPathExpression which can then be used for (repeated) evaluations.
+
{{domxref("document.createNSResolver","document.createNSResolver(Node resolver)")}}
+
Creates an {{domxref("XPathNSResolver")}} object.
+
{{domxref("document.evaluate","document.evaluate(String expression, Node contextNode, XPathNSResolver resolver, Number type, Object result)")}}
+
Evaluates an XPath expression.
+
+ +

Extension for HTML documents

+ +

The Document interface for HTML documents inherit from the {{domxref("HTMLDocument")}} interface or, since HTML5,  is extended for such documents:

+ +
+
{{domxref("document.clear()")}} {{non-standard_inline}} {{Deprecated_inline}}
+
In majority of modern browsers, including recent versions of Firefox and Internet Explorer, this method does nothing.
+
{{domxref("document.close()")}}
+
Closes a document stream for writing.
+
{{domxref("document.execCommand","document.execCommand(String command[, Boolean showUI[, String value]])")}}
+
On an editable document, executes a formating command.
+
{{domxref("document.getElementsByName","document.getElementsByName(String name)")}}
+
Returns a list of elements with the given name.
+
{{domxref("document.getSelection()")}}
+
Returns a {{domxref("Selection")}} object related to text selected in the document.
+
{{domxref("document.hasFocus()")}}
+
Returns true if the focus is currently located anywhere inside the specified document.
+
{{domxref("document.open()")}}
+
Opens a document stream for writing.
+
{{domxref("document.queryCommandEnabled","document.queryCommandEnabled(String command)")}}
+
Returns true if the formating command can be executed on the current range.
+
{{domxref("document.queryCommandIndeterm","document.queryCommandIndeterm(String command)")}}
+
Returns true if the formating command is in an indeterminate state on the current range.
+
{{domxref("document.queryCommandState","document.queryCommandState(String command)")}}
+
Returns true if the formating command has been executed on the current range.
+
{{domxref("document.queryCommandSupported","document.queryCommandSupported(String command)")}}
+
Returns true if the formating command is supported on the current range.
+
{{domxref("document.queryCommandValue","document.queryCommandValue(String command)")}}
+
Returns the current value of the current range for a formating command.
+
{{domxref("document.write","document.write(String text)")}}
+
Writes text in a document.
+
{{domxref("document.writeln","document.writeln(String text)")}}
+
Writes a line of text in a document.
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Selection API', '', 'Extend Document and GlobalEventHandlers')}}{{Spec2('Selection API')}}Adds onselectstart and onselectionchange.
{{SpecName('DOM1','#i-Document','Document')}}{{Spec2('DOM1')}}Initial definition for the interface
{{SpecName('DOM2 Core','#i-Document','Document')}}{{Spec2('DOM2 Core')}}Supersede DOM 1
{{SpecName('DOM3 Core','#i-Document','Document')}}{{Spec2('DOM3 Core')}}Supersede DOM 2
{{SpecName('DOM WHATWG','#interface-document','Document')}}{{Spec2('DOM WHATWG')}}Intend to supersede DOM 3
{{SpecName('HTML WHATWG','dom.html#the-document-object','Document')}}{{Spec2('HTML WHATWG')}}Turn the {{domxref("HTMLDocument")}} interface into a Document extension.
{{SpecName('DOM3 XPath','xpath.html#XPathEvaluator','XPathEvaluator')}}{{Spec2('DOM3 XPath')}}Define the {{domxref("XPathEvaluator")}} interface which extend document.
{{SpecName('HTML Editing','#dom-document-getselection','Document')}}{{Spec2('HTML Editing')}}Extend the Document interface
{{SpecName('CSSOM View','#extensions-to-the-document-interface','Document')}}{{Spec2('CSSOM View')}}Extend the Document interface
{{SpecName('CSSOM','#extensions-to-the-document-interface','Document')}}{{Spec2('CSSOM')}}Extend the Document interface
{{SpecName('Pointer Lock','#extensions-to-the-document-interface','Document')}}{{Spec2('Pointer Lock')}}Extend the Document interface
+ +

Browser compatibility notes

+ +

Firefox notes

+ +

Mozilla defines a set of non-standard properties made only for XUL content:

+ +
+
{{domxref("document.currentScript")}} {{non-standard_inline}} {{gecko_minversion_inline("2.0")}}
+
Returns the {{HTMLElement("script")}} element that is currently executing.
+
{{domxref("document.documentURIObject")}} {{gecko_minversion_inline("1.9")}}
+
(Mozilla add-ons only!) Returns the {{Interface("nsIURI")}} object representing the URI of the document. This property only has special meaning in privileged JavaScript code (with UniversalXPConnect privileges).
+
{{domxref("document.popupNode")}}
+
Returns the node upon which a popup was invoked.
+
{{domxref("document.tooltipNode")}}
+
Returns the node which is the target of the current tooltip.
+
+ +

Mozilla also define some non-standard methods:

+ +
+
{{domxref("document.execCommandShowHelp")}} {{obsolete_inline("14.0")}}
+
This method never did anything and always threw an exception, so it was removed in Gecko 14.0 {{geckoRelease("14.0")}}.
+
{{domxref("document.getBoxObjectFor")}} {{obsolete_inline}}
+
Use the {{domxref("Element.getBoundingClientRect()")}} method instead.
+
{{domxref("document.loadOverlay")}} {{Fx_minversion_inline("1.5")}}
+
Loads a XUL overlay dynamically. This only works in XUL documents.
+
{{domxref("document.queryCommandText")}} {{obsolete_inline("14.0")}}
+
This method never did anything but throw an exception, and was removed in Gecko 14.0 {{geckoRelease("14.0")}}.
+
+ +

Internet Explorer notes

+ +

Microsoft defines some non-standard properties:

+ +
+
{{domxref("document.fileSize")}}* {{non-standard_inline}} {{obsolete_inline}}
+
Returns size in bytes of the document. Starting with Internet Explorer 11, that property is no longer supported. See MSDN.
+
Internet Explorer does not support all methods from the Node interface in the Document interface:
+
+ +
+
{{domxref("document.contains")}}
+
As a work-around, document.body.contains() can be used.
+
+ +

 

diff --git a/files/id/web/api/document/links/index.html b/files/id/web/api/document/links/index.html new file mode 100644 index 0000000000..4a2d6a5a1b --- /dev/null +++ b/files/id/web/api/document/links/index.html @@ -0,0 +1,101 @@ +--- +title: Document.links +slug: Web/API/Document/links +tags: + - API + - Document + - Property + - Reference +translation_of: Web/API/Document/links +--- +

{{ APIRef("DOM") }}

+ +

Properti links mengembalikan sebuah collection dari semua elemen {{HTMLElement("area")}} dan elemen {{HTMLElement("a")}} pada sebuah dokumen dengan sebuah nilai pada atribut href .

+ +

Sintaks

+ +
nodeList = document.links
+
+ +

Contoh

+ +
var links = document.links;
+for(var i = 0; i < links.length; i++) {
+  var linkHref = document.createTextNode(links[i].href);
+  var lineBreak = document.createElement("br");
+  document.body.appendChild(linkHref);
+  document.body.appendChild(lineBreak);
+}
+
+ +

Spesifikasi

+ + + + + + + + + + + + + + + + + + + +
SpesifikasiStatusComment
{{SpecName('HTML WHATWG', '#dom-document-links', 'Document.links')}}{{ Spec2('HTML WHATWG') }} 
{{SpecName("DOM2 HTML", "html.html#ID-7068919", "document.links")}}{{Spec2("DOM2 HTML")}}Initial definition
+ +

Kompabilitas browser

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
diff --git a/files/id/web/api/document/write/index.html b/files/id/web/api/document/write/index.html new file mode 100644 index 0000000000..ac3912c415 --- /dev/null +++ b/files/id/web/api/document/write/index.html @@ -0,0 +1,77 @@ +--- +title: Document.write() +slug: Web/API/Document/write +tags: + - API + - DOM + - Method + - Reference +translation_of: Web/API/Document/write +--- +
{{ ApiRef("DOM") }}
+ +

Menuliskan teks string ke sebuah dokumen stream yang dibuka dengan document.open().

+ +
Catatan: ketika document.write menulis ke dokumen stream, memanggil document.write pada sebuah dokumen tertutup (termuat), dokumen secara otomatis memanggil document.open, yang akan menghapus dokumen.
+ +

Sintaks

+ +
document.write(markup);
+
+ +

markup merupakan sebuah string yang berisi teks untuk ditulis ke dalam dokumen.

+ +

Contoh

+ +
<html>
+
+<head>
+<title>write example</title>
+
+<script>
+
+function newContent()
+{
+alert("load new content");
+document.open();
+document.write("<h1>Out with the old - in with the new!</h1>");
+document.close();
+}
+
+</script>
+</head>
+
+<body onload="newContent();">
+<p>Some original document content.</p>
+</body>
+</html>
+
+ +

Catatan

+ +

Menulis ke sebuah dokumen yang telah dimuat tanpa memanggil document.open() akan secara otomatis melakukan panggilan document.open. Setelah selesai menulis, disarankan untuk memanggil document.close(), untuk meminta browser untuk menyelesaikan memuat halaman. Teks yang anda tulis akan di parse ke dalam stuktur model dokumen tersebut. Pada contoh diatas, elemen h1 menjadi sebuah node pada document.

+ +

Jika pemanggilan document.write() merpakan embeded pada inline tag html <script> tag, maka tidak akan memanggil document.open(). Sebagai contoh:

+ +
<script>
+  document.write("<h1>Main title</h1>")
+</script>
+
+ +
Catatan: document.write an document.writeln tidak berfungsi di dokumen XHTML ( anda akan mendapat peringatan "Operation is not supported" [NS_ERROR_DOM_NOT_SUPPORTED_ERR] error pada konsole). Ini terjadi ketika membuka sebuah file lokal dengan ekstensi file .xhtml atau dokumen lain yang disajikan dengan MIME type application/xhtml+xml . Informasi lengkap tersedia di W3C XHTML FAQ.
+ +
Catatan: document.write pada script deferred atau asynchronous akan diabaikan, dan anda mendapatkan peringatan error "A call to document.write() from an asynchronously-loaded external script was ignored" pada konsole.
+ +

Spesifikasi

+ + + +

Lihat juga

+ + diff --git a/files/id/web/api/event/currenttarget/index.html b/files/id/web/api/event/currenttarget/index.html new file mode 100644 index 0000000000..f44c5d54a9 --- /dev/null +++ b/files/id/web/api/event/currenttarget/index.html @@ -0,0 +1,127 @@ +--- +title: Event.currentTarget +slug: Web/API/Event/currentTarget +tags: + - API + - DOM + - Gecko + - events +translation_of: Web/API/Event/currentTarget +--- +

{{APIRef("DOM")}}

+ +

Mengidentifikasi event untuk target saat ini, seperti ketika event melalui DOM. Event tersebut selalu mengacu kepada lemen yang terikat dengan event handler, sebagai lawan dari event.target yang mana mengidentifikasi elemen ketika event tersebut terjadi.

+ +

Contoh

+ +

event.currentTarget sangat menarik untuk digunakan ketika menyatukan event handler yang sama ke beberapa element.

+ +
function hide(e){
+  e.currentTarget.style.visibility = "hidden";
+  console.log(e.currentTarget);
+  // Ketika fungsi digunakan seperti event handler: this === e.currentTarget
+}
+
+var ps = document.getElementsByTagName('p');
+
+for(var i = 0; i < ps.length; i++){
+  // console: print the clicked <p> element
+  ps[i].addEventListener('click', hide, false);
+}
+// console: print <body>
+document.body.addEventListener('click', hide, false);
+
+// click dan paragraph akan menghilang
+
+ +

Spesifikasi

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpesifikasiStatusKomentar
{{SpecName("DOM WHATWG", "#dom-event-currenttarget", "Event.currentTarget")}}{{Spec2("DOM WHATWG")}} 
{{SpecName("DOM4", "#dom-event-currenttarget", "Event.currentTarget")}}{{Spec2("DOM4")}} 
{{SpecName("DOM3 Events", "#dfn-current-event-target", "current event target")}}{{Spec2("DOM3 Events")}} 
{{SpecName("DOM2 Events", "#Events-Event-currentTarget", "Event.currentTarget")}}{{Spec2("DOM2 Events")}}Definisi awal
+ +

Kesesuaian browser

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}[1]{{CompatVersionUnknown}}10.0
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}10.0
+
+ +

[1] Dalam Internet Explorer 6 sampai 8, event modelnya berbeda. Event listener(s) nya terikat dengan metode non-standard {{domxref("EventTarget.attachEvent")}}. Dalam model ini, tidak ada yang setara dengan event.currentTarget dan this adalah objek global. Satu solusin untuk meniru fitur event.currentTarget adalah dengan cara membungkus handler anda di dalam fungsi memanggil handler tersebut menggunakan Function.prototype.call dengan elemen sebagai argumen awal. Dengan cara ini, this akan menampilkan hasil yang diharapkan.

+ +

Lihat juga

+ +

Perbandingan dari Event Targets

diff --git a/files/id/web/api/event/index.html b/files/id/web/api/event/index.html new file mode 100644 index 0000000000..952082247b --- /dev/null +++ b/files/id/web/api/event/index.html @@ -0,0 +1,149 @@ +--- +title: Event +slug: Web/API/Event +tags: + - API + - DOM + - Event + - Interface + - Reference +translation_of: Web/API/Event +--- +

{{APIRef("DOM")}}

+ +

Antarmuka Event mewakili setiap event pada DOM. mengandung properti umum dan method ke setiap event.

+ +

Banyak sekali antarmuka lain yang menginplementasikan antarmuka Event, baik secara langsung atau dengan mengimplementsikan antarmuka lain dimana diantaranya:

+ +
+ +
+ +

Konstruktor

+ +
+
{{domxref("Event.Event", "Event()")}}
+
Membuat sebuah object Event
+
+ +

Properti

+ +

Antarmuka ini tidak mewarisi properti manapun.

+ +
+
{{domxref("Event.bubbles")}} {{readonlyinline}}
+
Sebuah boolean yang menunjukan apakah event bubbles melalui DOM atau tidak.
+
{{domxref("Event.cancelBubble")}} {{non-standard_inline}}
+
Alternatif non-standar untuk {{domxref("Event.stopPropagation()")}}.
+
{{domxref("Event.cancelable")}} {{readonlyinline}}
+
Sebuah boolean yang menunjukan apakah event bisa dibatalkan.
+
{{domxref("Event.currentTarget")}} {{readonlyinline}}
+
Sebuah referensi untuk target terdaftar saat ini untuk event.
+
{{domxref("Event.defaultPrevented")}} {{readonlyinline}}
+
Menunjukan apakah {{domxref("event.preventDefault()")}} telah dipanggil pada event atau belum.
+
{{domxref("Event.eventPhase")}} {{readonlyinline}}
+
Menunjukan fase aliran event yang sedang diproses.
+
{{domxref("Event.explicitOriginalTarget")}} {{non-standard_inline}} {{readonlyinline}}
+
Eksplisit target dari event (Mozilla-specific).
+
{{domxref("Event.originalTarget")}} {{non-standard_inline}} {{readonlyinline}}
+
Target dari event, sebelum penargetan ulang lain (Mozilla-specific).
+
{{domxref("Event.returnValue")}} {{non-standard_inline}}
+
Alternatif nonstandard untuk {{domxref("Event.preventDefault()")}} dan {{domxref("Event.defaultPrevented")}}. (spesifik Internet Explorer lama)
+
{{domxref("Event.srcElement")}} {{non-standard_inline}}
+
Alias nonstandard untuk {{domxref("Event.target")}}. (spesifik Internet Explorer lama)
+
{{domxref("Event.target")}} {{readonlyinline}}
+
Sebuah referensi untuk target dimana event pertama kali dikirimkan.
+
{{domxref("Event.timeStamp")}} {{readonlyinline}}
+
Waktu ketika event dibuat.
+
{{domxref("Event.type")}} {{readonlyinline}}
+
Nama dari event (case-insensitive).
+
{{domxref("Event.isTrusted")}} {{readonlyinline}}
+
Menunjukan apakah event di terima browser atau tidak (mis. ketika user klik) atau dengan sebuah script (menggunakan sebuah method event buatan, seperti event.initEvent)
+
+ +

Method

+ +

Antarmuka ini tidak mewarisi method manapun.

+ +
+
{{domxref("Event.initEvent()")}} {{deprecated_inline}}
+
Menginisialisasi nilai dari Event yang dibuat. Jika event telah dikirimkan, method ini tidak akan digunakan.
+
{{domxref("Event.preventBubble()")}} {{non-standard_inline}} {{Obsolete_inline(24)}}
+
Mencegah event agar tidak menggelegak. Usang, gunakan {{domxref("event.stopPropagation")}} sebagai gantinya.
+
{{domxref("Event.preventCapture()")}} {{non-standard_inline}} {{Obsolete_inline(24)}}
+
Usang, gunakan {{domxref("event.stopPropagation")}} sebagai gantinya.
+
{{domxref("Event.preventDefault()")}}
+
Membatalkan event event (jika cancelable).
+
{{domxref("Event.stopImmediatePropagation()")}}
+
Khusus untuk event ini, tidak ada listener lain yang akan dipanggil. Baik yang ada pada elemen yang sama, maupunyang ada pada elemen yang akan di lalui nantinya (pada fase capture, misalnya)
+
{{domxref("Event.stopPropagation()")}}
+
Menghentikan penyebaran events lebih jauh pada DOM.
+
{{domxref("Event.getPreventDefault()")}} {{non-standard_inline}}
+
Non-standard. Mengembailkan nilai dari {{domxref("Event.defaultPrevented")}}. Gunakan {{domxref("Event.defaultPrevented")}} sebagai gantinya.
+
+ +

Lihat Juga

+ + diff --git a/files/id/web/api/event/target/index.html b/files/id/web/api/event/target/index.html new file mode 100644 index 0000000000..52397c0827 --- /dev/null +++ b/files/id/web/api/event/target/index.html @@ -0,0 +1,90 @@ +--- +title: Event.target +slug: Web/API/Event/target +translation_of: Web/API/Event/target +--- +
{{ApiRef("DOM")}}
+ +

The target property of the {{domxref("Event")}} interface is a reference to the object onto which the event was dispatched. It is different from {{domxref("Event.currentTarget")}} when the event handler is called during the bubbling or capturing phase of the event.

+ +

Syntax

+ +
var theTarget = event.target;
+ +

Value

+ +

{{domxref("EventTarget")}}

+ +

Example

+ +

Properti event.target dapat digunakan untuk mengimplementasikan event delegation.

+ +
// Membuat sebuah list
+var ul = document.createElement('ul');
+document.body.appendChild(ul);
+
+var li1 = document.createElement('li');
+var li2 = document.createElement('li');
+ul.appendChild(li1);
+ul.appendChild(li2);
+
+function hide(e){
+  // e.target refers to the clicked <li> element
+  // This is different than e.currentTarget which would refer to the parent <ul> in this context
+  e.target.style.visibility = 'hidden';
+}
+
+// Attach the listener to the list
+// It will fire when each <li> is clicked
+ul.addEventListener('click', hide, false);
+
+ +

Spesifikasi

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("DOM WHATWG", "#dom-event-target", "Event.target")}}{{Spec2("DOM WHATWG")}}
{{SpecName("DOM4", "#dom-event-target", "Event.target")}}{{Spec2("DOM4")}}
{{SpecName("DOM2 Events", "#Events-Event-target", "Event.target")}}{{Spec2("DOM2 Events")}}Initial definition
+ +

Browser compatibility

+ + + +

{{Compat("api.Event.target")}}

+ +

Compatibility notes

+ +

On IE 6-8 the event model is different. Event listeners are attached with the non-standard {{domxref('EventTarget.attachEvent()')}} method. In this model, the event object has a {{domxref('Event.srcElement')}} property, instead of the target property, and it has the same semantics as Event.target.

+ +
function hide(e) {
+  // Support IE6-8
+  var target = e.target || e.srcElement;
+  target.style.visibility = 'hidden';
+}
+
+ +

See also

+ + diff --git a/files/id/web/api/fetch_api/index.html b/files/id/web/api/fetch_api/index.html new file mode 100644 index 0000000000..ad64ee4558 --- /dev/null +++ b/files/id/web/api/fetch_api/index.html @@ -0,0 +1,88 @@ +--- +title: Fetch API +slug: Web/API/Fetch_API +translation_of: Web/API/Fetch_API +--- +
{{DefaultAPISidebar("Fetch API")}}
+ +

Fetch Data API menyediakan antarmuka untuk pemanggilan sumber daya data(termasuk di seluruh jaringan). Ini akan terasa familiar bagi siapa saja yang telah menggunakan {{DOMxRef("XMLHttpRequest")}}, tetapi untuk API yang terbaru menyediakan serangkaian fitur yang lebih kuat dan fleksibel.

+ +

Konsep dan Penggunaan

+ +

"Fetch" / pengambilan resource data menyediakan definisi umum yaitu objek{{DOMxRef("Request")}} dan {{DOMxRef("Response")}} atau permintaan dan tanggapan(dan hal-hal lain yang kaitannya dengan permintaan jaringan/"HTTP"). Ini akan memungkinkan "request" dan "response" tersebut untuk digunakan di mana pun mereka dibutuhkan di waktu selanjutnya, apakah itu untuk pekerja layanan/service workers(biasanya PWA), Cache API dan hal-hal serupa lainnya yang menangani atau mengubah permintaan dan tanggapan, ataupun juga segala jenis kasus penggunaan yang mungkin mengharuskan Anda untuk menghasilkan response/tanggapan Anda sendiri secara terprogram (baca aja:scr otomatis).

+ +

Ini juga memberikan definisi untuk konsep yang berhubungan dengan request dan response seperti halnya : CORS dan sumber semantik header HTTP, yang menggantikan definisi mereka yang terpisah di topik lain (bukan disini bahasannya/beda topik).

+ +

Untuk membuat permintaan dan mengambil sumber daya data, bisa menggunakan metode {{DOMxRef("WindowOrWorkerGlobalScope.fetch()")}} ini. Metode ini diimplementasikan dalam beberapa antarmuka aplikasi, khususnya pada {{DOMxRef("Window")}} dan {{DOMxRef("WorkerGlobalScope")}}Ini membuatnya tersedia dalam hampir semua konteks yang mana anda mungkin menginginkan untuk mengambil sumber data / resource nya.

+ +

Metode fetch() mengambil satu argumen yang wajib disertakan, path(sbg gambaran kalau di html : tag a dg atribut href) ke sumber data yang anda inginkan untuk mengambilnya. Hal ini mampu untuk mengembalikan hasil/return {{DOMxRef("Promise")}} yang memutuskan ke {{DOMxRef("Response")}} kepada permintaan itu sendiri, apakah hal tersebut berhasil atau tidak pada saat terjadi response/tanggapan sumber data. Anda juga bisa secara opsional mengirimkan objek pilihan initsebagai argumen keduanya (lihat {{DOMxRef("Request")}}).

+ +

Setelah {{DOMxRef("Response")}} telah dipanggil, ada sejumlah metode yang tersedia untuk menentukan apa saja konten tubuh(pikirkan pada elemen html) dan bagaimana penanganannya (lihat {{DOMxRef("Body")}}).

+ +

Anda juga bisa membuat permintaan dan response secara langsung menggunakan {{DOMxRef("Request.Request", "Request()")}}dan konstruktor {{DOMxRef("Response.Response", "Response()")}}, namun Anda tidak bisa melakukan ini secara langsung. Malahan, ini lebih cenderung sebagai hasil dari aksi yang dilakukan oleh API yang lainnya (misalnya, {{DOMxRef("FetchEvent.respondWith()")}} dari service workers (kalo loe yang main teknologinya PWA pasti tau coy)).

+ +
+

Catatan : Cari tahu lebih lanjut mengenai penggunaan fitur Fetch API di cara menggunakan fetch , dan pelajari konsepnya di konsep dasar fetch .

+
+ +

Batalkan fetch

+ +

Web browser sudah mulai menambahkan dukungan eksperimental untuk antarmuka {{DOMxRef("AbortController")}} dan {{DOMxRef("AbortSignal")}}(alias API Abort), yang memungkinkan operasi seperti Fetch dan XHR untuk dibatalkan apabila mereka belum selesai secara sempurna dipanggil. Lihat halaman antarmuka untuk detail lebih lanjut.

+ +

Browsers have started to add experimental support for the {{DOMxRef("AbortController")}} and {{DOMxRef("AbortSignal")}} interfaces (aka The Abort API), which allow operation

+ +

 

+ +

Antarmuka metode Fetch

+ +
+
WindowOrWorkerGlobalScope.fetch()
+
Metode fetch() yang digunakan untuk mengambil sumber data.
+
Headers
+
Merupakan header respons / permintaan, memungkinkan Anda untuk menanyakannya(query) dan mengambil tindakan yang berbeda dimana ini tergantung pada hasilnya.
+
Request
+
Merupakan permintaan sumber data.
+
Response
+
Merupakan respons terhadap permintaan.
+
+ +

Fetch mixin

+ +
+
{{DOMxRef("Body")}}
+
Menyediakan metode yang berkaitan dengan konten pada respons / permintaan, memungkinkan Anda untuk menyatakan jenis kontennya dan bagaimana penanganannya.
+
+ +

Spesifikasi

+ + + + + + + + + + + + + + +
SpesifikasiStatusKeterangan
{{SpecName("Fetch")}}{{Spec2("Fetch")}}Definisi awal
+ +

Kompatibilitas Browser

+ + + +

{{Compat("api.WindowOrWorkerGlobalScope.fetch")}}

+ +

Lihat juga untuk 

+ + diff --git a/files/id/web/api/index.html b/files/id/web/api/index.html new file mode 100644 index 0000000000..bbbaf07d0a --- /dev/null +++ b/files/id/web/api/index.html @@ -0,0 +1,12 @@ +--- +title: Referensi API Web +slug: Web/API +tags: + - API + - Develop + - Web API +translation_of: Web/API +--- +

Saat menulis kode untuk Web menggunakan JavaScript, ada banyak API yang tersedia. Berikut adalah daftar semua antarmuka (atau dengan kata lain, tipe objek) yang dapat digunakan ketika mengembangkan aplikasi atau situs web.

+ +
{{APIListAlpha}}
diff --git a/files/id/web/api/mobile_connection_api/index.html b/files/id/web/api/mobile_connection_api/index.html new file mode 100644 index 0000000000..7b5462e2ef --- /dev/null +++ b/files/id/web/api/mobile_connection_api/index.html @@ -0,0 +1,149 @@ +--- +title: Mobile Connection +slug: Web/API/Mobile_Connection_API +translation_of: Archive/B2G_OS/API/Mobile_Connection_API +--- +

{{ draft }}

+

{{ non-standard_header() }}

+

{{ B2GOnlyHeader2('certified') }}

+

Summary

+

This API has 2 purposes:

+ +

As this API can access functionalities that can have an impact on the mobile plan subscribed by the user (some of the functionalities can cost money to use or can damage the ICC), it is restricted to certified applications only.

+

The main entry point for this API is the {{domxref("window.navigator.mozMobileConnection","navigator.mozMobileConnection")}} property which is an instance of the {{domxref("MozMobileConnection")}} interface.

+

State of mobile connection

+

The state of the mobile connection is divided in two: on the one hand the voice connection, on the other hand the data connection. The data related to each type of connection are accessible through the {{domxref("MozMobileConnection.voice")}} and {{domxref("MozMobileConnection.data")}} properties which both return a {{domxref("MozMobileConnectionInfo")}} object.

+

Those objects give access to all information related to the quality of the network (signal strength, quality of the signal, position of the network's cells, restricted usage, roaming, etc.), and related to the carrier operating the network.

+
var cnx = navigator.mozMobileConnection;
+
+console.log("The voice operator is " + cnx.voice.network.longName);
+
+if (cnx.voice.connected) {
+  console.log("The signal has a strength of " + (+cnx.voice.relSignalStrength) + "%");
+} else {
+  console.log("The state of the connection is: " + cnx.voice.state);
+}
+
+

ICC Functionalities

+

The functionalities available for the ICC can be divided into two categories: the management of the ICC itself and the use of the integrated command available within the STK (SIM Application Toolkit).

+

Basic actions

+

The {{domxref("MozMobileConnection")}} provides a set of methods to deal with common behaviors on ICCs.

+
+

Note: All original methods from the MozMobileConnection interface are fully asynchronous. They all return a {{domxref("DOMRequest")}} object which has an onsuccess and onerror event handler to handle the success or failure of the method call.

+
+

Card lock

+

As long as a card is locked, a user is unable to use it to reach its mobile network. It's possible to manage the card lock with the {{domxref("MozMobileConnection.getCardLock","getCardLock()")}}, {{domxref("MozMobileConnection.setCardLock","setCardLock()")}}, and {{domxref("MozMobileConnection.unlockCardLock","unlockCardLock()")}} methods.

+

If {{domxref("MozMobileConnection.getCardLock","getCardLock()")}} allows to get some detailed information about the lock, it's also possible to have quick info about the lock through {{domxref("MozMobileConnection.cardState")}} which returns a string representing the current state of the lock.

+
+

Note: Even if the state change requests are successfully handled, it does not mean that the operations are necessarily successful. For that reason, any change in the card state is tracked independently through events:

+ +
+
var cnx = navigator.mozMobileConnection;
+
+function unlockCard() {
+  var unlockOptions = {
+    lockType: "pin",
+    pin     : prompt("Please, enter your PIN")
+  }
+
+  var unlock = cnx.unlockCardLock(unlockOptions);
+
+  unlock.onsuccess = function () {
+    console.log("The card has successfully handled the PIN number.");
+
+    if (this.result.success === false) {
+      if (this.result.retryCount > 0) {
+        console.log("But you mistyped your PIN, you have " + this.result.retryCount + " tries left.");
+      } else {
+        console.log("But your card is hard locked, you need to contact your carrier to get a special unlocking code.");
+      }
+    }
+  }
+
+  unlock.onerror = function () {
+    console.log("Hu! Something goes very wrong!")
+  }
+}
+
+cnx.addEventListener('icccardlockerror', function () {
+  // In case of error, ask the user for his PIN again
+  unlockCard();
+});
+
+cnx.addEventListener('cardsatechange', function () {
+  // In case the card state change and required to be unlocked
+  if (cnx.cardState === 'pinRequired') {
+    unlockCard();
+  }
+}
+
+// First call to unlockCard if required
+if (cnx.cardState === 'pinRequired') {
+  unlockCard();
+}
+
+

MMI Messages

+

MMI messages are human understandable code that, once typed with a phone keyboard, allow to trigger specific action from the RIL or get response from the network through a USSD request. A common example is typing a short code to get the IMEI phone number.

+

Such messages are sent using the {{domxref("MozMobileConnection.sendMMI()")}} method (and can be canceled with {{domxref("MozMobileConnection.cancelMMI","cancelMMI()")}}). Even if it will return a {{domxref("DOMRequest")}} object, the response to such messages are handled in two ways:

+ +
var cnx = navigator.mozMobileConnection;
+
+cnx.addEventHandler('ussdreceived', function (evt) {
+  console.log('Network message: ' + evt.data.message);
+});
+
+var MMIRequest = cnx.sendMMI(prompt('Provide a valid MMI'));
+
+MMIRequest.onerror = function() {
+  console.log("Mmmh... Something goes wrong.");
+}
+
+

Call forwarding options

+

Call forwarding options allow to define how a call can or cannot be forwarded to another phone number.

+

Those options are handled with the {{domxref("MozMobileConnection.getCallForwardingOption","getCallForwardingOption()")}} and {{domxref("MozMobileConnection.setCallForwardingOption","setCallForwardingOption()")}} methods.

+
var options = {
+  action      : MozMobileCFInfo.CALL_FORWARD_ACTION_ENABLE,
+  reason      : MozMobileCFInfo.CALL_FORWARD_REASON_UNCONDITIONAL,
+  serviceClass: MozMobileConnectionInfo.ICC_SERVICE_CLASS_VOICE,
+  number      : prompt('To which phone number would you wish to forward the calls?'),
+  timeSeconds : 5
+};
+
+var setOption = navigator.mozMobileConnection.setCallForwardingOption(options);
+
+setOption.onsuccess = function () {
+  console.log('Options successfully set');
+}
+
+setOption.onerror = function () {
+  console.log('Unable to set options: ' + this.error.name);
+}
+
+

STK commands

+

The STK commands depend on many factors (carriers, chips model, etc.) but can always be accessed through the {{domxref("MozMobileConnection.icc")}} property which returns a {{domxref("MozIccManager")}} object.

+
+

Warning: It's recommended to use the STK command only if you already know exactly what you are doing, as a misusage can damage the chip and make it unusable.

+
+

Specification

+

Not part of any specification.

+

See also

+ diff --git a/files/id/web/api/navigator/index.html b/files/id/web/api/navigator/index.html new file mode 100644 index 0000000000..9d40d2eee4 --- /dev/null +++ b/files/id/web/api/navigator/index.html @@ -0,0 +1,149 @@ +--- +title: Navigator +slug: Web/API/Navigator +tags: + - API + - HTML DOM + - HTML-DOM + - Interface + - JavaScript + - NeedsTranslation + - Reference + - TopicStub + - Web Performance +translation_of: Web/API/Navigator +--- +

{{ apiref() }}

+ +

Antarmuka Navigator mewakili negara dan identitas pengguna. Memungkinkan script untuk melakukan query dan mendaftarkan diri untuk melakukan suatu aktivitas.

+ +

Objek Navigator dapat dipanggil menggunakan properti {{domxref("Window.navigator")}}.

+ +

Properti

+ +

Bukan turunan dari properti manapun, namun menginplementasikan yang didefinisikan di  {{domxref("NavigatorID")}}, {{domxref("NavigatorLanguage")}}, {{domxref("NavigatorOnLine")}}, {{domxref("NavigatorContentUtils")}}, {{domxref("NavigatorStorageUtils")}}, {{domxref("NavigatorCookies")}}, {{domxref("NavigatorConcurrentHardware")}}, {{domxref("NavigatorPlugins")}}, dan {{domxref("NavigatorUserMedia")}}.

+ +

Standard

+ +
+
{{domxref("Navigator.activeVRDisplays")}} {{readonlyInline}}{{experimental_inline}}
+
Mengembalikan sebuah array yang berisi setiap objek {{domxref("VRDisplay")}} yang menyajikan ({{domxref("VRDisplay.ispresenting")}} adalah true).
+
{{domxref("NavigatorID.appCodeName")}} {{readonlyInline}}{{experimental_inline}}
+
Mengembalikan internal nama "code" browser. Jangan mengandalkan properti ini untuk mengembalikan nilai yang benar.
+
{{domxref("NavigatorID.appName")}} {{readonlyInline}}{{experimental_inline}}
+
Mengembalikan  {{domxref("DOMString")}} dengan nama official dari browser. Jangan mengandalkan properti ini untuk mengembalikan nilai yang benar.
+
{{domxref("NavigatorID.appVersion")}} {{readonlyInline}}{{experimental_inline}}
+
Mengembalikan versi browser sebagai {{domxref("DOMString")}}. Jangan mengandalkan properti ini untuk mengembalikan nilai yang benar.
+
{{domxref("Navigator.battery")}} {{readonlyInline}}
+
Mengembalikan objek {{domxref("BatteryManager")}} yang memberikan informasi tentang status isi baterai.
+
{{domxref("Navigator.connection")}} {{readonlyInline}}{{experimental_inline}}
+
Menyediakan sebuah objek {{domxref("NetworkInformation")}} yang berisi informasi tentang koneksi jaringan pada perangkat.
+
{{domxref("Navigator.geolocation")}} {{readonlyInline}}
+
Mengembalikan objek {{domxref("Geolocation")}} yang memungkinkan untuk mengakses lokasi perangkat.
+
{{domxref("NavigatorConcurrentHardware.hardwareConcurrency")}} {{readOnlyInline}}
+
Mengembalikan jumlah inti logical processor yag tersedia.
+
{{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}}
+
Mengembalikan {{domxref("DOMString")}} berdasarkan bahasa yang digunakan, biasanya bahasa UI pada browser. Nilai null akan dikembalikan jika tidak diketahui.
+
{{domxref("NavigatorLanguage.languages")}} {{readonlyInline}}
+
Mengembalikan sebuah array dari {{domxref("DOMString")}} berdasarkan bahasa yang diketahui pengguna, berdasarkan pengaturan.
+
{{domxref("NavigatorPlugins.mimeTypes")}} {{readonlyInline}}{{experimental_inline}}
+
Mengembalikan daftar {{domxref("MimeTypeArray")}} dari tipe MIME yang didukung oleh browser.
+
{{domxref("NavigatorOnLine.onLine")}} {{readonlyInline}}
+
Mengembalikan sebuah {{domxref("Boolean")}} yang menunjukan apakah browser dalam keadaan online.
+
{{domxref("Navigator.oscpu")}}
+
Mengembalikan sebuah string berdasarkan sistem operasi.
+
{{domxref("Navigator.permissions")}} {{readonlyinline}}{{experimental_inline}}
+
Mengembalikan objek {{domxref("Permissions")}} yang dapat digunakan untuk query dan membaharui status izin dari APIs yang di cakup di Permissions API.
+
{{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

+ +
+

Firefox OS devices adds more non-standard properties. You can consult them on the Firefox OS Navigator extensions article.

+
+ +

{{domxref("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.credentials")}} {{non-standard_inline}}
+
Returns the {{domxref("CredentialsContainer")}} interface which exposes methods to request credentials and notify the user agent when interesting events occur such as successful sign in or sign out. 
+
{{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("Navigator.mediaDevices")}} {{non-standard_inline}}
+
Returns a reference to the {{domxref("MediaDevices")}} interface.
+
{{domxref("Navigator.mozNotification")}} {{deprecated_inline("22")}} {{non-standard_inline}}
+ {{domxref("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("Navigator.presentation")}} {{non-standard_inline}}
+
Returns a reference to the {{domxref("Presentation")}} API.
+
{{domxref("Navigator.productSub")}} {{non-standard_inline}}
+
Returns the build number of the current browser (e.g., "20060909").
+
{{domxref("Navigator.securitypolicy")}} {{non-standard_inline}}
+
Returns an empty string. In Netscape 4.7x, returns "US & CA domestic policy" or "Export policy".
+
{{domxref("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("Navigator.vendor")}} {{non-standard_inline}}
+
Returns the vendor name of the current browser (e.g., "Netscape6").
+
{{domxref("Navigator.vendorSub")}} {{non-standard_inline}}
+
Returns the vendor version number (e.g. "6.1").
+
{{domxref("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("Navigator.getVRDisplays()")}} {{experimental_inline}}
+
Returns a promise that resolves to an array of {{domxref("VRDisplay")}} objects representing any available VR devices connected to the computer.
+
{{domxref("Navigator.getUserMedia", "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("Navigator.registerContentHandler()")}}
+
Allows web sites to register themselves as a possible handler for a given MIME type.
+
{{domxref("Navigator.registerProtocolHandler()")}}
+
Allows web sites to register themselves as a possible handler for a given protocol.
+
{{domxref("Navigator.requestMediaKeySystemAccess()")}} {{experimental_inline}}
+
Returns a {{jsxref("Promise")}} for a MediaKeySystemAccess object.
+
{{domxref("Navigator.sendBeacon()")}}{{experimental_inline}}
+
Used to asynchronously transfer small HTTP data from the User Agent to a web server.
+
{{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

+ +
+

Firefox OS devices adds more non-standard methods. You can consult them on the Firefox OS Navigator extensions article.

+
+ +

{{domxref("Navigator.mozIsLocallyAvailable()")}} {{non-standard_inline}}

+ +
+
Lets code check to see if the document at a given URI is available without using the network.
+
{{domxref("Navigator.mozPay()")}} {{non-standard_inline}}
+
Allows in-app payment.
+
diff --git a/files/id/web/api/navigator/mediadevices/index.html b/files/id/web/api/navigator/mediadevices/index.html new file mode 100644 index 0000000000..b51d697dd9 --- /dev/null +++ b/files/id/web/api/navigator/mediadevices/index.html @@ -0,0 +1,47 @@ +--- +title: Navigator.mediaDevices +slug: Web/API/Navigator/mediaDevices +translation_of: Web/API/Navigator/mediaDevices +--- +
{{APIRef("Media Capture and Streams")}}
+ +

The Navigator.mediaDevices read-only property returns a {{domxref("MediaDevices")}} object, which provides access to connected media input devices like cameras and microphones, as well as screen sharing.

+ +

Syntax

+ +
var mediaDevices = navigator.mediaDevices;
+
+ +

Return value

+ +

The {{domxref("MediaDevices")}} singleton object. Usually, you just use this object's members directly, such as by calling {{domxref("navigator.mediaDevices.getUserMedia()")}}.

+ +

Spesifikasi

+ + + + + + + + + + + + + + +
SpesifikasiStatusComment
{{SpecName('Media Capture', '#mediadevices', 'NavigatorUserMedia.mediaDevices')}}{{Spec2('Media Capture')}}Initial definition.
+ +

Browser compatibility

+ + + +

{{Compat("api.Navigator.mediaDevices")}}

+ +

Lihat juga

+ + diff --git a/files/id/web/api/navigator/serviceworker/index.html b/files/id/web/api/navigator/serviceworker/index.html new file mode 100644 index 0000000000..2599ecf9a2 --- /dev/null +++ b/files/id/web/api/navigator/serviceworker/index.html @@ -0,0 +1,101 @@ +--- +title: Navigator.serviceWorker +slug: Web/API/Navigator/serviceWorker +tags: + - API + - Reference + - Service Worker +translation_of: Web/API/Navigator/serviceWorker +--- +

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

+ +

Navigator.serviceWorker adalah properti yang hanya bisa dibaca, mengembalikan objek {{domxref("ServiceWorkerContainer")}} untuk dokumen terkait, yang memberikan akses untuk registrasi, penghapusan, upgrade, dan berkomunikasi dengan {{domxref("ServiceWorker")}}.

+ +

Sintaks

+ +
var workerContainerInstance = navigator.serviceWorker;
+
+ +

Nilai

+ +

{{domxref("ServiceWorkerContainer")}}.

+ +

Spesifikasi

+ + + + + + + + + + + + + + +
SpesifikasiStatusComment
{{SpecName('Service Workers', '#navigator-service-worker', 'navigator.serviceWorker')}}{{Spec2('Service Workers')}}Initial definition.
+ +

Kompabilitas Browser

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FiturChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Dukungan dasar{{CompatChrome(40.0)}}{{ CompatGeckoDesktop("44.0") }}[1]{{CompatNo}}24{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FiturAndroidFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Dukungan dasar{{CompatUnknown}}{{ CompatGeckoMobile("44.0") }}{{ CompatVersionUnknown }}{{CompatNo}}{{CompatUnknown}}{{CompatNo}}{{CompatUnknown}}
+
+ +

[1] Service workers (dan Push) telah di non-aktifkan di Firefox 45 Extended Support Release (ESR.)

+ +

Lihat Juga

+ + diff --git a/files/id/web/api/service_worker_api/index.html b/files/id/web/api/service_worker_api/index.html new file mode 100644 index 0000000000..345f183563 --- /dev/null +++ b/files/id/web/api/service_worker_api/index.html @@ -0,0 +1,283 @@ +--- +title: Service Worker API +slug: Web/API/Service_Worker_API +tags: + - API + - Landing + - NeedsTranslation + - Offline + - Overview + - Reference + - Service Workers + - TopicStub + - Workers +translation_of: Web/API/Service_Worker_API +--- +
+

{{ServiceWorkerSidebar}}

+ +

{{ SeeCompatTable() }}

+ +

Service workers essentially act as proxy servers that sit between web applications, and the browser and network (when available). They are intended to (amongst other things) enable the creation of effective offline experiences, intercepting network requests and taking appropriate action based on whether the network is available and updated assets reside on the server. They will also allow access to push notifications and background sync APIs.

+
+ +

Service worker concepts and usage

+ +

A service worker is an event-driven worker registered against an origin and a path. It takes the form of a JavaScript file that can control the web page/site it is associated with, intercepting and modifying navigation and resource requests, and caching resources in a very granular fashion to give you complete control over how your app behaves in certain situations (the most obvious one being when the network is not available.)

+ +

A service worker is run in a worker context: it therefore has no DOM access, and runs on a different thread to the main JavaScript that powers your app, so it is not blocking. It is designed to be fully async; as a consequence, APIs such as synchronous XHR and localStorage can't be used inside a service worker.

+ +

Service workers only run over HTTPS, for security reasons. Having modified network requests wide open to man in the middle attacks would be really bad.

+ +
+

Note: Service Workers win over previous attempts in this area such as AppCache because they don't make assumptions about what you are trying to do and then break when those assumptions are not exactly right; you have granular control over everything.

+
+ +
+

Note: Service workers make heavy use of promises, as generally they will wait for responses to come through, after which they will respond with a success or failure action. The promises architecture is ideal for this.

+
+ +

Registration

+ +

A service worker is first registered using the {{domxref("ServiceWorkerContainer.register()")}} method. If successful, your service worker will be downloaded to the client and attempt installation/activation (see below) for URLs accessed by the user inside the whole origin, or inside a subset specified by you.

+ +

Download, install and activate

+ +

At this point, your service worker will observe the following lifecycle:

+ +
    +
  1. Download
  2. +
  3. Install
  4. +
  5. Activate
  6. +
+ +

The service worker is immediately downloaded when a user first accesses a service worker–controlled site/page.

+ +

After that it is downloaded every 24 hours or so. It *may* be downloaded more frequently, but it must be downloaded every 24h to prevent bad scripts from being annoying for too long.

+ +

Installation is attempted when the downloaded file is found to be new — either different to an existing service worker (byte-wise compared), or the first service worker encountered for this page/site.

+ +

If this is the first time a service worker has been made available, installation is attempted, then after a successful installation it is activated.

+ +

If there is an existing service worker available, the new version is installed in the background, but not yet activated — at this point it is called the worker in waiting. It is only activated when there are no longer any pages loaded that are still using the old service worker. As soon as there are no more such pages still loaded, the new service worker activates (becoming the active worker).

+ +

You can listen out for the {{domxref("InstallEvent")}}; a standard action is to prepare your service worker for usage when this fires, for example by creating a cache using the built in storage API, and placing assets inside it that you'll want for running your app offline.

+ +

There is also an activate event. The point where this event fires is generally a good time to clean up old caches and other things associated with the previous version of your service worker.

+ +

Your service worker can respond to requests using the {{domxref("FetchEvent")}} event. You can modify the response to these requests in any way you want, using the {{domxref("FetchEvent.respondWith") }} method.

+ +
+

Note: Because oninstall/onactivate could take a while to complete, the service worker spec provides a waitUntil method that, when called oninstall or onactivate, passes a promise. Functional events are not dispatched to the service worker until the promise successfully resolves.

+
+ +

For a complete tutorial to show how to build up your first basic example, read Using Service Workers.

+ +

Other use case ideas

+ +

Service workers are also intended to be used for such things as:

+ + + +

In the future, service workers will be able to do a number of other useful things for the web platform that will bring it closer towards native app viability. Interestingly, other specifications can and will start to make use of the service worker context, for example:

+ + + +

Interfaces

+ +
+
{{domxref("Cache") }}
+
Represents the storage for {{domxref("Request")}} / {{domxref("Response")}} object pairs that are cached as part of the {{domxref("ServiceWorker")}} life cycle.
+
{{domxref("CacheStorage") }}
+
Represents the storage for {{domxref("Cache")}} objects. It provides a master directory of all the named caches that a {{domxref("ServiceWorker")}} can access and maintains a mapping of string names to corresponding {{domxref("Cache")}} objects.
+
{{domxref("Client") }}
+
Represents the scope of a service worker client. A service worker client is either a document in a browser context or a {{domxref("SharedWorker")}}, which is controlled by an active worker.
+
{{domxref("Clients") }}
+
Represents a container for a list of {{domxref("Client")}} objects; the main way to access the active service worker clients at the current origin.
+
{{domxref("ExtendableEvent") }}
+
Extends the lifetime of the install and activate events dispatched on the {{domxref("ServiceWorkerGlobalScope")}} as part of the service worker lifecycle. This ensures that any functional events (like {{domxref("FetchEvent")}}) are not dispatched to the {{domxref("ServiceWorker")}} until it upgrades database schemas, deletes outdated cache entries, etc.
+
{{domxref("ExtendableMessageEvent") }}
+
The event object of a {{event("message_(ServiceWorker)","message")}} event fired on a service worker (when a channel message is received on the {{domxref("ServiceWorkerGlobalScope")}} from another context) — extends the lifetime of such events.
+
{{domxref("FetchEvent") }}
+
The parameter passed into the {{domxref("ServiceWorkerGlobalScope.onfetch")}} handler, FetchEvent represents a fetch action that is dispatched on the {{domxref("ServiceWorkerGlobalScope")}} of a {{domxref("ServiceWorker")}}. It contains information about the request and resulting response, and provides the {{domxref("FetchEvent.respondWith", "FetchEvent.respondWith()")}} method, which allows us to provide an arbitrary response back to the controlled page.
+
{{domxref("InstallEvent") }}
+
The parameter passed into the {{domxref("ServiceWorkerGlobalScope.oninstall", "oninstall")}} handler, the InstallEvent interface represents an install action that is dispatched on the {{domxref("ServiceWorkerGlobalScope")}} of a {{domxref("ServiceWorker")}}. As a child of {{domxref("ExtendableEvent")}}, it ensures that functional events such as {{domxref("FetchEvent")}} are not dispatched during installation. 
+
{{domxref("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.
+
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Service Workers')}}{{Spec2('Service Workers')}}Initial definition.
+ +

Browser compatibility

+ +
{{ CompatibilityTable() }}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(40.0)}}{{ CompatGeckoDesktop("44.0") }}[1]{{ CompatNo() }}24{{ CompatNo() }}
install/activate events{{ CompatChrome(40.0) }}{{ CompatGeckoDesktop("44.0") }}[1]{{ CompatNo() }}{{ CompatVersionUnknown() }}{{ CompatNo() }}
fetch event/request/
+ respondWith()
{{CompatChrome(40.0)}}{{ CompatGeckoDesktop("44.0") }}[1]{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}
caches/cache +

{{CompatChrome(42.0)}}

+
{{ CompatGeckoDesktop("39.0") }}[1]{{ 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() }}
+
+ +

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

+ +

See also

+ + diff --git a/files/id/web/api/service_worker_api/using_service_workers/index.html b/files/id/web/api/service_worker_api/using_service_workers/index.html new file mode 100644 index 0000000000..b88643f6ed --- /dev/null +++ b/files/id/web/api/service_worker_api/using_service_workers/index.html @@ -0,0 +1,539 @@ +--- +title: Menggunakan Service Workers +slug: Web/API/Service_Worker_API/Using_Service_Workers +tags: + - Paduan + - ServiceWorker + - dasar +translation_of: Web/API/Service_Worker_API/Using_Service_Workers +--- +

{{ServiceWorkerSidebar}}

+ +

{{ SeeCompatTable() }}

+ +
+

Artikel ini memberikan informasi mengenai cara memulai dan menggunakan Service Workers, Termasuk arsitektur dasar, mendaftarkan service worker, penginstalan dan proses aktivasi service worker, memperbaharui service worker, kontrol cache dan custom response, Semuanya dalam konteks aplikasi sederhana dengan fungsi offline. 

+
+ +

Premis Service Workers

+ +

Salah satu masalah utama yang dialami pengguna web selama bertahun - tahun adalah hilangnya konektivitas. Bahkan aplikasi terbaik didunia sekalipun akan memberikan pengalaman pengguna yang buruk jika tidak bisa di muat atau di download. Berbagai upaya menciptakan teknologi telah dilakukan untuk memecahkan masalah tersebut, Agar halaman Offline dapat digunakan, dan beberapa masalah telah diselesaikan.Tapi masalah utamanya masih belum ada mekanisame kontrol yang terbaik untuk semua permintaan aset cache dan kostum jaringan.
+
+ Pada upaya sebelumnya — AppCache — dilihat sebagai ide yang bagus karena disana anda juga bisa menentukan aset untuk dicache dengan mudah. Namun, itu membuat asumsi tentang ketika anda mencoba dan kemudian pecah dengan mengerikan ketika aplikasi anda tidak mengikuti asumsi premis. Baca artikel Jake Archibald's Application Cache is a Douchebag untuk lebih detail.

+ +
+

Catatan: Pada firefox 44, ketika AppCache digunakan untuk menyediakan layanan offline untuk suatu halaman, pesan peringatan sekarang akan ditampilkan di console menyarankan pengembang untuk menggunakan Service workers  ({{bug("1204581")}}.)

+
+ +

Service worker seharusnya telah memecahkan masalah ini. Syntax pada service worker lebih kompleks di bandingkan AppCache, tapi kesamaanya adalah anda bisa menggunkan javascript untuk mengontrol AppCache anda secara tersirat dengan derajat grunality yang lebih bagus, memungkinkan anda untuk menangani masalah ini dan banyak lagi. Dengan menggunakan Service worker anda bisa mengatur aplikasi untuk menggunakan aset utama, sehingga memberikan pengalaman utama bahkan saat offline, sebelum mendapatkan lebih banyak data dari jaringan (biasa disebut sebagai Offline First). Ini sudah tersedia dengan aplikasi asli, yang merupakan salah satu alasan utama aplikasi asli sering dipilih lebih dari aplikasi web.

+ +

Persiapan bermain dengan service worker

+ +

Banyak fitur service worker saat ini telah di aktifkan secara default pada browser versi terbaru yang mendukung. Tapi jika anda menemui kode demo tidak bekerja pada versi browser anda, mungkin anda perlu mengaktifkan preferensi:

+ + + +

Anda perlu menyajikan kode dengan menggunakan HTTPS — Service Workers dibatasi dengan hanya dapat di jalankan pada HTTPS untuk alasan keamanan. Github merupakan salah satu tempat yang di sarankan untuk bereksperimen, karena mendukung HTTPS.

+ +

Arsitektur dasar

+ +

Dengan service workers, langkah - langkah umum berikut perlu diamati untuk konfigurasi dasar:

+ +
    +
  1. URL service worker diambil di daftarkan melalui {{domxref("serviceWorkerContainer.register()")}}.
  2. +
  3. Jika sukses, service worker dijalankan di {{domxref("ServiceWorkerGlobalScope") }}; pada dasarnya ini merupakan hal yang sepesial dari konteks worker, menjalankan tread script utama untuk pengeksekusian, tanpa dukungan akses DOM.
  4. +
  5. Sekarang service worker telah siap untuk memproses event.
  6. +
  7. Instalasai service worker dicoba ketika service worker mengontrol halaman yang diakses setelah dan sebelumnya. Even Install akan selalu di kirim pertama kali ke service workerr ( ini bisa digunakan untuk memulai proses untuk mengumpulkan IndexedDB, dan mencache aset situs). Sama halnya seperti prosedur penginstalan asli atau aplikasi firefox OS — memungkinkan semuanya tersedia untuk digunakan secara offline.
  8. +
  9. Ketika handler oninstall selesai, service worker ditetapkan untuk diinstall.
  10. +
  11. Selanjutnya adalah aktivasi. Ketika service worker terinstall, selanjutnya akan menerima event activate. Penggunaan utama dari onactivate adalah untuk membersihkan sumberdaya yang digunakan pada versi sebelumnya.
  12. +
  13. Service Worker sekarang dapat mengontrol halaman, tapi hanya yang di buka setelah register() telah sukses. misal dokumen mulai aktif dengan atau tanpa Service Worker dan menjaganya selama masih digunakan. Jadi dokumen harus di muat ulang agar benar - benar terkontrol.
  14. +
+ +

+ +

Grafik dibawah menunjukan ringkasan dari event yang tersedia pada service worker:

+ +

install, activate, message, fetch, sync, push

+ +

Promis

+ +

Promis adalah mekanisme yang sebagian besar digunakan untuk menjalankan operasi secara asinkron, dengan bergantung pada pencapaian satu dan lainnya. Ini merupakan pusat dari cara kerja service workers.
+
+ Promis bisa digunakan untuk melakukan banyak hal, tapi untuk saat ini, yang perlu anda tahu adalah jika sesuatu yang mengembalikan promise, anda bisa menambahkan.then() di akhir dan menambahkan callback di dalamnya untuk mengetahui apakah berhasil, gagal da lainnya., atau anda bisa menambahkan .catch() di akhir jika anda ingin menambahkan calback status gagal.

+ +

Mari bandingkan kesamaan struktur callback tradisional synchronous dan promise asynchronous.

+ +

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

Pada contoh pertama, kita perlu mengunggu myFunction() untuk dijalankan dan mengembalikan nilai sebelum kode lain bisa dijalankan. Pada contoh kedua, myFunction() mengembalikan promise untuk nilai, kemudian semua kode dapat di bawa untuk dapat dijalankan. Ketika promise diselesaikan, kode didalamnya bisa dijalankan secara asynchronously.
+
+ Sebagai contoh nyata — jika kita ingin memuat gambar secara dinamic, tapi kita ingin memastikan bahwa gambar tersebut di muat terlebih dahulu sebelum di tampilkan? Hal standar ini yang ingin dilakukan, tapi ini akan sedikit sulit. Kita bisa mengunakan .onload untuk hanya menampilkan gambar setelah di muat, tapi bagaimana dengan event yang memulai sebelum kita memulai melacaknya ? kita bisa mencoba melakukannya dengan menggunakan.complete, tapi ini tetap tidak foolproof, dan bagaimana dengan lebih dari satu gambar? Dan, ummm, ini tetap synchronous, Jadi di blok di tread utama.
+
+ Gantinya, kita bisa membuat promis kita sendiri untuk mengatasi kasus seperi ini. (Lihat contoh Promises test untuk kode sumber, atau Lihat cara kerja secara live.)

+ +

{{note("Implementasi service worker akan mengutamakan menggunakan caching dan onfetch daripada XMLHttpRequest API. Fitur tersebut tidak di gunakan disini jadi anda hanya fokus pada penggunaan Promises.")}}

+ +
function imgLoad(url) {
+  return new Promise(function(resolve, reject) {
+    var request = new XMLHttpRequest();
+    request.open('GET', url);
+    request.responseType = 'blob';
+
+    request.onload = function() {
+      if (request.status == 200) {
+        resolve(request.response);
+      } else {
+        reject(Error('Image didn\'t load successfully; error code:' + request.statusText));
+      }
+    };
+
+    request.onerror = function() {
+      reject(Error('There was a network error.'));
+    };
+
+    request.send();
+  });
+}
+ +

Kita mengembalikan promis baru menggunakan konstruktor Promise(), di mana menggunakan argumen sebagai fungsi callback dengan parameter resolve dan reject. DImanapung di fungsi, kita perlu mendefinisikan apa yang terjadi untuk promise yang diselesaikan secara sukses atau ditolak — pada kasus ini mengembalikan status 200 OK atau tidak — dan kemudian memanggil  resolve ketika sukses, atau reject jika gagal. Semua konten dari fungsi ini adalah perangkat dasar XHR, jadi kita tidak perlu khawatir untuk saat ini.

+ +

Ketika memanggil fungsi imgLoad(), kita memanggilnya dengan menggunakan url gambar yang akan dimuat, seperti yang kita harapkan, namun kodenya sedikit berbeda:

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

Pada akhir pemanggilan fungsi, kita menggabungkan promise method then(), dimana terdiri dari dua fungsi — yang pertama akan di eksekusi ketika promise berhasil di selesaikan, dan yang kedua akan dipanggil ketika promise di tolak. Pada penyelesaian kasus, kita menampilkan gambar di dalam myImage dan menambahkannya ke body (dengan argumen request.response yang berada di dalam method resolve); pada kasus ditolak kita mengembalikan error di console.

+ +

Semua terjadi secara asynchronously.

+ +
+

Catatan: Anda juga bisa menggabungkan panggilan promise secara bersamaan, Misal:
+ myPromise().then(success, failure).then(success).catch(failure);

+
+ +
+

Catatan: Anda bisa mendapatkan lebih banyak informasi tentang promise dengan membaca tulisan Jake Archibald’s excellent JavaScript Promises: there and back again.

+
+ +

Demo service workers

+ +

Sebagai demonstrasi hanya sekedar dasar pendaftaran dan penginstalan service worker, kita membuat sebuah demo sederhana dengan nama sw-test, berupa galeri gambar Star wars Lego. Mengunakan fungsi dengan promise untuk membaca data gambar dari sebuah objek JSON dan memuat gambar menggunakan Ajax, Sebelum menamilkan gambar pada halaman. Kita akan semuanya tetap simple dan statis untuk saat ini. Di sini pendaftaran, instalasi, dan akativasi sebuah service worker, dan ketika semua spec di dukung oleh browsers maka semua file yang diperukan akan dicache untuk di muat secara offline!

+ +


+
+
+ Anda bisa melihat source code di GitHub, dan Melihat contoh secara live. The one bit we’ll call out here is the promise (see app.js lines 17-42), which is a modified version of what you read about above, in the Promises test demo. It is different in the following ways:

+ +
    +
  1. In the original, we only passed in a URL to an image we wanted to load. In this version, we pass in a JSON fragment containing all the data for a single image (see what they look like in image-list.js). This is because all the data for each promise resolve has to be passed in with the promise, as it is asynchronous. If you just passed in the url, and then tried to access the other items in the JSON separately when the for() loop is being iterated through later on, it wouldn’t work, as the promise wouldn’t resolve at the same time as the iterations are being done (that is a synchronous process.)
  2. +
  3. We actually resolve the promise with an array, as we want to make the loaded image blob available to the resolving function later on in the code, but also the image name, credits and alt text (see app.js lines 26-29). Promises will only resolve with a single argument, so if you want to resolve with multiple values, you need to use an array/object.
  4. +
  5. To access the resolved promise values, we then access this function as you’d then expect (see app.js lines 55-59.) This may seem a bit odd at first, but this is the way promises work.
  6. +
+ +

Enter Service workers

+ +

Now let’s get on to service workers!

+ +

Mendaftarkan worker

+ +

The first block of code in our app’s JavaScript file — app.js — is as follows. This is our entry point into using service workers.

+ +
if ('serviceWorker' in navigator) {
+  navigator.serviceWorker.register('/sw-test/sw.js', { scope: '/sw-test/' }).then(function(reg) {
+    // registration worked
+    console.log('Registration succeeded. Scope is ' + reg.scope);
+  }).catch(function(error) {
+    // registration failed
+    console.log('Registration failed with ' + error);
+  });
+};
+ +
    +
  1. The outer block performs a feature detection test to make sure service workers are supported before trying to register one.
  2. +
  3. Next, we use the {{domxref("ServiceWorkerContainer.register()") }} function to register the service worker for this site, which is just a JavaScript file residing inside our app (note this is the file's URL relative to the origin, not the JS file that references it.)
  4. +
  5. The scope parameter is optional, and can be used to specify the subset of your content that you want the service worker to control. In this case, we have specified '/sw-test/', which means all content under the app's origin. If you leave it out, it will default to this value anyway, but we specified it here for illustration purposes.
  6. +
  7. The .then() promise function is used to chain a success case onto our promise structure.  When the promise resolves successfully, the code inside it executes.
  8. +
  9. Finally, we chain a .catch() function onto the end that will run if the promise is rejected.
  10. +
+ +

This registers a service worker, which runs in a worker context, and therefore has no DOM access. You then run code in the service worker outside of your normal pages to control their loading.
+
+ A single service worker can control many pages. Each time a page within your scope is loaded, the service worker is installed against that page and operates on it. Bear in mind therefore that you need to be careful with global variables in the service worker script: each page doesn’t get its own unique worker.

+ +
+

Note: Your service worker functions like a proxy server, allowing you to modify requests and responses, replace them with items from its own cache, and more.

+
+ +
+

Note: One great thing about service workers is that if you use feature detection like we’ve shown above, browsers that don’t support service workers can just use your app online in the normal expected fashion. Furthermore, if you use AppCache and SW on a page, browsers that don’t support SW but do support AppCache will use that, and browsers that support both will ignore the AppCache and let SW take over.

+
+ +

Kenapa service worker saya gagal didaftarkan?

+ +

Hal tersebut bisa terjadi karena alasan berikut:

+ +
    +
  1. Anda tidak menjalankan aplikasi dari HTTPS.
  2. +
  3. Path dari file service worker anda tidak ditulis dengan benar — seharusnya di tulis relatif terhadap origin, bukan root dari direktori aplikasi anda. Pada contoh, worker berada di https://mdn.github.io/sw-test/sw.js, dan root aplikasi di https://mdn.github.io/sw-test/. Namun path harus ditulis /sw-test/sw.js, bukan /sw.js.
  4. +
  5. The service worker being pointed to is on a different origin to that of your app. This is also not allowed.
  6. +
+ +

+ +

Also note:

+ + + +

Install dan activasi: mengumpulkan cache

+ +

Setelah service worker anda terdaftar, browser akan menginstall dan mengaktifkan service worker untuk halaman/situs anda.
+
+ Event instal dijalankan ketika install selesai dengan sukses. Event install biasanya digunakan oleh browser untuk mengumpulkan cache offline dari aset yang akan digunakan untuk menjalankan aplikasi anda secara offline. Untuk melakukannya, kita menggunakan Storage API dari Service Worker — {{domxref("cache")}} —  global pada service worker yang memungkinkan kita menympan aset yang diterima dari response, dan di sandikan berdasarkan request. API ini sama halnya dengan cache pada browser umumnya, tapi lebih spesifik ke domain. Ini persis hinga anda tidak menginginkan — anda punya kontrol penuh.

+ +
+

Note: The Cache API is not supported in every browser. (See the {{anch("Browser support")}} section for more information.) If you want to use this now, you could consider using a polyfill like the one available in Google's Topeka demo, or perhaps store your assets in IndexedDB.

+
+ +

Let’s start this section by looking at a code sample — this is the first block you’ll find in our service worker:

+ +
this.addEventListener('install', function(event) {
+  event.waitUntil(
+    caches.open('v1').then(function(cache) {
+      return cache.addAll([
+        '/sw-test/',
+        '/sw-test/index.html',
+        '/sw-test/style.css',
+        '/sw-test/app.js',
+        '/sw-test/image-list.js',
+        '/sw-test/star-wars-logo.jpg',
+        '/sw-test/gallery/',
+        '/sw-test/gallery/bountyHunters.jpg',
+        '/sw-test/gallery/myLittleVader.jpg',
+        '/sw-test/gallery/snowTroopers.jpg'
+      ]);
+    })
+  );
+});
+ +
    +
  1. Here we add an install event listener to the service worker (hence this), and then chain a {{domxref("ExtendableEvent.waitUntil()") }} method onto the event — this ensures that the Service Worker will not install until the code inside waitUntil() has successfully occurred.
  2. +
  3. Inside waitUntil() we use the caches.open() method to create a new cache called v1, which will be version 1 of our site resources cache. This returns a promise for a created cache; once resolved, we then call a function that calls addAll() on the created cache, which for its parameter takes an array of origin-relative URLs to all the resources you want to cache.
  4. +
  5. If the promise is rejected, the install fails, and the worker won’t do anything. This is ok, as you can fix your code and then try again the next time registration occurs.
  6. +
  7. After a successful installation, the service worker activates. This doesn’t have much of a distinct use the first time your service worker is installed/activated, but it means more when the service worker is updated (see the {{anch("Updating your service worker") }} section later on.)
  8. +
+ +
+

Note: localStorage works in a similar way to service worker cache, but it is synchronous, so not allowed in service workers.

+
+ +
+

Note: IndexedDB can be used inside a service worker for data storage if you require it.

+
+ +

Custom responses to requests

+ +

Now you’ve got your site assets cached, you need to tell service workers to do something with the cached content. This is easily done with the fetch event.

+ +

+ +

A fetch event fires every time any resource controlled by a service worker is fetched, which includes the documents inside the specified scope, and any resources referenced in those documents (for example if index.html makes a cross origin request to embed an image, that still goes through its service worker.)

+ +

You can attach a fetch event listener to the service worker, then call the respondWith() method on the event to hijack our HTTP responses and update them with your own magic.

+ +
this.addEventListener('fetch', function(event) {
+  event.respondWith(
+    // magic goes here
+  );
+});
+ +

We could start by simply responding with the resource whose url matches that of the network request, in each case:

+ +
this.addEventListener('fetch', function(event) {
+  event.respondWith(
+    caches.match(event.request);
+  );
+});
+ +

caches.match(event.request) allows us to match each resource requested from the network with the equivalent resource available in the cache, if there is a matching one available. The matching is done via url and vary headers, just like with normal HTTP requests.

+ +

Let’s look at a few other options we have when defining our magic (see our Fetch API documentation for more information about {{domxref("Request")}} and {{domxref("Response")}} objects.)

+ +
    +
  1. +

    The {{domxref("Response.Response","Response()")}} constructor allows you to create a custom response. In this case, we are just returning a simple text string:

    + +
    new Response('Hello from your friendly neighbourhood service worker!');
    +
  2. +
  3. +

    This more complex Response below shows that you can optionally pass a set of headers in with your response, emulating standard HTTP response headers. Here we are just telling the browser what the content type of our synthetic response is:

    + +
    new Response('
    + +

    Hello from your friendly neighbourhood service worker!

    + ', { headers: { 'Content-Type': 'text/html' } })
  4. +
  5. +

    If a match wasn’t found in the cache, you could tell the browser to simply {{domxref("GlobalFetch.fetch","fetch")}} the default network request for that resource, to get the new resource from the network if it is available:

    + +
    fetch(event.request)
    +
  6. +
  7. +

    If a match wasn’t found in the cache, and the network isn’t available, you could just match the request with some kind of default fallback page as a response using {{domxref("CacheStorage.match","match()")}}, like this:

    + +
    caches.match('/fallback.html');
    +
  8. +
  9. +

    You can retrieve a lot of information about each request by calling parameters of the {{domxref("Request")}} object returned by the {{domxref("FetchEvent")}}:

    + +
    event.request.url
    +event.request.method
    +event.request.headers
    +event.request.body
    +
  10. +
+ +

Recovering failed requests

+ +

So caches.match(event.request) is great when there is a match in the service worker cache, but what about cases when there isn’t a match? If we didn’t provide any kind of failure handling, our promise would reject and we would just come up against a network error when a match isn’t found.

+ +

Fortunately service workers’ promise-based structure makes it trivial to provide further options towards success. We could do this:

+ +
this.addEventListener('fetch', function(event) {
+  event.respondWith(
+    caches.match(event.request).catch(function() {
+      return fetch(event.request);
+    })
+  );
+});
+ +

If the promise rejects, the catch() function returns the default network request for the resource instead, meaning that those who have network available can just load the resource from the server.

+ +

If we were being really clever, we would not only request the resource from the network; we would also save it into the cache so that later requests for that resource could be retrieved offline too! This would mean that if extra images were added to the Star Wars gallery, our app could automatically grab them and cache them. The following would do the trick:

+ +
this.addEventListener('fetch', function(event) {
+  event.respondWith(
+    caches.match(event.request).catch(function() {
+      return fetch(event.request).then(function(response) {
+        return caches.open('v1').then(function(cache) {
+          cache.put(event.request, response.clone());
+          return response;
+        });
+      });
+    })
+  );
+});
+ +

Here we return the default network request with return fetch(event.request), which returns a promise. When this promise is resolved, we respond by running a function that grabs our cache using caches.open('v1'); this also returns a promise. When that promise resolves, cache.put() is used to add the resource to the cache. The resource is grabbed from event.request, and the response is then cloned with response.clone() and added to the cache. The clone is put in the cache, and the original response is returned to the browser to be given to the page that called it.

+ +

Why? This is because request and response streams can only be read once.  In order to return the response to the browser and put it in the cache we have to clone it. So the original gets returned to the browser and the clone gets sent to the cache.  They are each read once.

+ +

The only trouble we have now is that if the request doesn’t match anything in the cache, and the network is not available, our request will still fail. Let’s provide a default fallback so that whatever happens, the user will at least get something:

+ +
this.addEventListener('fetch', function(event) {
+  event.respondWith(
+    caches.match(event.request).catch(function() {
+      return fetch(event.request).then(function(response) {
+        return caches.open('v1').then(function(cache) {
+          cache.put(event.request, response.clone());
+          return response;
+        });
+      });
+    }).catch(function() {
+      return caches.match('/sw-test/gallery/myLittleVader.jpg');
+    })
+  );
+});
+ +

We have opted for this fallback image because the only updates that are likely to fail are new images, as everything else is depended on for installation in the install event listener we saw earlier.

+ +

Updated code pattern suggestion

+ +

This uses more standard promise chaining and returns the response to the document without having to wait for caches.open() to resolve:

+ +
this.addEventListener('fetch', function(event) {
+  var response;
+  event.respondWith(caches.match(event.request).catch(function() {
+    return fetch(event.request);
+  }).then(function(r) {
+    response = r;
+    caches.open('v1').then(function(cache) {
+      cache.put(event.request, response);
+    });
+    return response.clone();
+  }).catch(function() {
+    return caches.match('/sw-test/gallery/myLittleVader.jpg');
+  }));
+});
+ +

Membaharui service worker

+ +

If your service worker has previously been installed, but then a new version of the worker is available on refresh or page load, the new version is installed in the background, but not yet activated. It is only activated when there are no longer any pages loaded that are still using the old service worker. As soon as there are no more such pages still loaded, the new service worker activates.

+ +

You’ll want to update your install event listener in the new service worker to something like this (notice the new version number):

+ +
this.addEventListener('install', function(event) {
+  event.waitUntil(
+    caches.open('v2').then(function(cache) {
+      return cache.addAll([
+        '/sw-test/',
+        '/sw-test/index.html',
+        '/sw-test/style.css',
+        '/sw-test/app.js',
+        '/sw-test/image-list.js',
+
+             …
+
+              // include other new resources for the new version...
+      ]);
+    });
+  );
+});
+ +

While this happens, the previous version is still responsible for fetches. The new version is installing in the background. We are calling the new cache v2, so the previous v1 cache isn't disturbed.

+ +

When no pages are using the current version, the new worker activates and becomes responsible for fetches.

+ +

Deleting old caches

+ +

You also get an activate event. This is a generally used to do stuff that would have broken the previous version while it was still running, for example getting rid of old caches. This is also useful for removing data that is no longer needed to avoid filling up too much disk space — each browser has a hard limit on the amount of cache storage that a given service worker can use. The browser does its best to manage disk space, but it may delete the Cache storage for an origin.  The browser will generally delete all of the data for an origin or none of the data for an origin.

+ +

Promises passed into waitUntil() will block other events until completion, so you can rest assured that your clean-up operation will have completed by the time you get your first fetch event on the new cache.

+ +
this.addEventListener('activate', function(event) {
+  var cacheWhitelist = ['v2'];
+
+  event.waitUntil(
+    caches.keys().then(function(keyList) {
+      return Promise.all(keyList.map(function(key) {
+        if (cacheWhitelist.indexOf(key) === -1) {
+          return caches.delete(key);
+        }
+      }));
+    })
+  );
+});
+ +

Dev tools

+ +

Chrome has chrome://inspect/#service-workers, which shows current service worker activity and storage on a device, and chrome://serviceworker-internals, which shows more detail and allows you to start/stop/debug the worker process. In the future they will have throttling/offline modes to simulate bad or non-existent connections, which will be a really good thing.

+ +

Firefox has also started to implement some useful tools related to service workers:

+ + + +

Spesifikasi

+ + + + + + + + + + + + + + +
SpesifikasiStatusComment
{{SpecName('Service Workers', '')}}{{Spec2('Service Workers')}}Initial definition.
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FiturChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Dukungan dasar{{CompatChrome(40.0)}}{{ CompatGeckoDesktop("33.0") }}[1]{{CompatNo}}24{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FiturAndroidChrome for AndroidFirefox Mobile (Gecko)Firefox OSIE PhoneOpera MobileSafari Mobile
Dukungan dasar{{CompatNo}}{{CompatChrome(40.0)}}{{ CompatVersionUnknown }}{{ CompatVersionUnknown }}{{CompatNo}}{{ CompatVersionUnknown() }}{{CompatNo}}
+
+ +

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

+ +

Lihat juga

+ + diff --git a/files/id/web/api/serviceworker/index.html b/files/id/web/api/serviceworker/index.html new file mode 100644 index 0000000000..26787c6031 --- /dev/null +++ b/files/id/web/api/serviceworker/index.html @@ -0,0 +1,157 @@ +--- +title: ServiceWorker +slug: Web/API/ServiceWorker +tags: + - API + - Draft + - Offline + - Referensi + - ServiceWorker +translation_of: Web/API/ServiceWorker +--- +
{{SeeCompatTable}}{{APIRef("Service Workers API")}}
+ +

Antarmuka ServiceWorker dari ServiceWorker API menyediakan referensi kepada service worker. Konteks multi browsing (mis. halaman, pekerja, dll.) dapat dikaitkan dengan service worker yang sama, masing - masing melalui objek ServiceWorker tersendiri.

+ +

Objek ServiceWorker tersedia di properti {{domxref("ServiceWorkerRegistration.active")}} , dan properti {{domxref("ServiceWorkerContainer.controller")}}  — ini adalah service worker yang aktif dan mengontrol halaman (service worker telah sukses terdaftar, dan halaman yang di kontrol telah di muat kembali.)

+ +

Antarmuka ServiceWorker terbagi sebagai rangkaian siklus event — install dan activate — dan fungsional event termasuk fetch. Objek ServiceWorker memiliki keterkaitan {{domxref("ServiceWorker.state")}}, berdasarkan siklusnya.

+ +

Properti

+ +

Antarmuka ServiceWorker mewarisi properti dari induknya, {{domxref("Worker")}}.

+ +
+
{{domxref("ServiceWorker.scriptURL")}} {{readonlyinline}}
+
Mengembalikan serialisasi script URL ServiceWorker didefinisikan sebagai bagian dari {{domxref("ServiceWorkerRegistration")}}. URL harus dari origin yang sama dengan dokumen yang mendaftarkan ServiceWorker.
+
{{domxref("ServiceWorker.state")}} {{readonlyinline}}
+
Mengembalikan status keadaan service worker. Akan mengembalikan salah satu dari nilai berikut: installing, installed, activating, activated, atau redundant.
+
+ +

Event handlers

+ +
+
{{domxref("ServiceWorker.onstatechange")}} {{readonlyinline}}
+
Properti {{domxref("EventListener")}} dipanggil setiap kali event type statechange di jalankan; Pada dasarnya dijalankan setiap ada perubahan pada {{domxref("ServiceWorker.state")}}.
+
+ +

Method

+ +

Antarmuka ServiceWorker mewarisi method dari induknya, {{domxref("Worker")}}, dengan pengecualian {{domxref("Worker.terminate")}} — tidak harus dapat diakses dari service workers.

+ +

Contoh

+ +

Ini adalah potongan kode dari service worker registration-events sample (live demo). Kode memperhatikan setiap perubahan di {{domxref("ServiceWorker.state")}} dan mengembalikan nilainya.

+ +
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 = 'Menginstall';
+        } else if (registration.waiting) {
+            serviceWorker = registration.waiting;
+            document.querySelector('#kind').textContent = 'Mengunggu';
+        } else if (registration.active) {
+            serviceWorker = registration.active;
+            document.querySelector('#kind').textContent = 'Aktif';
+        }
+        if (serviceWorker) {
+            // logState(serviceWorker.state);
+            serviceWorker.addEventListener('statechange', function (e) {
+                // logState(e.target.state);
+            });
+        }
+    }).catch (function (error) {
+        // Terjadi kesalahan saat mendaftarkan. File service-worker.js
+        // mungkin tidak tersedia atau terdapat sintaks yang error.
+    });
+} else {
+    // Browser ini tidak mendukung service worker.
+}
+ +

Spesifikasi

+ + + + + + + + + + + + + + +
SpesifikasiStatusComment
{{SpecName('Service Workers', '#service-worker-obj', 'ServiceWorker')}}{{Spec2('Service Workers')}}Definisi inisial
+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FiturChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Dukungan dasar{{CompatChrome(40.0)}}{{CompatGeckoDesktop("44.0")}}[1]{{CompatNo}}24{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
FiturAndroidAndroid WebviewFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Dukungan dasar{{CompatNo}}{{CompatNo}}{{CompatGeckoMobile("44.0")}}{{ CompatVersionUnknown }}{{CompatNo}}{{CompatUnknown}}{{CompatNo}}{{CompatChrome(40.0)}}
+
+ +

[1] Service workers (dan Push) telah di nonaktifkan di Firefox 45 Extended Support Release (ESR.)

+ +

See also

+ + diff --git a/files/id/web/api/serviceworkercontainer/index.html b/files/id/web/api/serviceworkercontainer/index.html new file mode 100644 index 0000000000..ab3f71a543 --- /dev/null +++ b/files/id/web/api/serviceworkercontainer/index.html @@ -0,0 +1,132 @@ +--- +title: ServiceWorkerContainer +slug: Web/API/ServiceWorkerContainer +tags: + - API + - Draft + - Interface + - NeedsTranslation + - Offline + - Reference + - Service Workers + - Service worker API + - ServiceWorkerContainer + - TopicStub + - Workers +translation_of: Web/API/ServiceWorkerContainer +--- +

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

+ +

The ServiceWorkerContainer interface of the Service Worker API provides an object representing the service worker as an overall unit in the network ecosystem, including facilities to register, unregister and update service workers, and access the state of service workers and their registrations.

+ +

Most importantly, it exposes the {{domxref("ServiceWorkerContainer.register", "ServiceWorkerContainer.register()")}} method used to register service workers, and the {{domxref("ServiceWorkerContainer.controller")}} property used to determine whether or not the current page is actively controlled.

+ +

Properties

+ +
+
{{domxref("ServiceWorkerContainer.controller")}} {{readonlyinline}}
+
Returns a {{domxref("ServiceWorker")}} object if its state is activated (the same object returned by {{domxref("ServiceWorkerRegistration.active")}}). This property returns null during a force-refresh request (Shift + refresh) or if there is no active worker.
+
+ +
+
{{domxref("ServiceWorkerContainer.ready")}} {{readonlyinline}}
+
Provides a way of delaying code execution until a service worker is active. It returns a {{jsxref("Promise")}} that will never reject, and which waits indefinitely until the {{domxref("ServiceWorkerRegistration")}} associated with the current page has an {{domxref("ServiceWorkerRegistration.active")}} worker. Once that condition is met, it resolves with the {{domxref("ServiceWorkerRegistration")}}.
+
+ +

Events

+ +
+
controllerchange
+
Occurs when the document's associated {{domxref("ServiceWorkerRegistration")}} acquires a new {{domxref("ServiceWorkerRegistration.active","active")}} worker.
+ Also available via the {{domxref("ServiceWorkerContainer.oncontrollerchange")}} property.
+
error
+
Fired whenever an error occurs in the associated service workers.
+ Also available via the {{domxref("ServiceWorkerContainer.onerror")}} property.
+
message
+
Occurs when incoming messages are received by the {{domxref("ServiceWorkerContainer")}} object (e.g. via a {{domxref("MessagePort.postMessage()")}} call.)
+ Also available via the {{domxref("ServiceWorkerContainer.onmessage")}} property.
+
+ +

Methods

+ +
+
{{domxref("ServiceWorkerContainer.register", "ServiceWorkerContainer.register()")}} 
+
Creates or updates a {{domxref("ServiceWorkerRegistration")}} for the given scriptURL.
+
{{domxref("ServiceWorkerContainer.getRegistration()")}}
+
Gets a {{domxref("ServiceWorkerRegistration")}} object whose scope matches the provided document URL.  The method returns a {{jsxref("Promise")}} that resolves to a {{domxref("ServiceWorkerRegistration")}} or undefined
+
{{domxref("ServiceWorkerContainer.getRegistrations()")}}
+
Returns all {{domxref("ServiceWorkerRegistration")}} objects associated with a ServiceWorkerContainer in an array.  The method returns a {{jsxref("Promise")}} that resolves to an array of {{domxref("ServiceWorkerRegistration")}}. 
+
{{domxref("ServiceWorkerContainer.startMessages()")}}
+
explicitly starts the flow of messages being dispatched from a service worker to pages under its control (e.g. sent via {{domxref("Client.postMessage()")}}). This can be used to react to sent messages earlier, even before that page's content has finished loading.
+
+ +

Examples

+ +

The example below first checks to see if the browser supports service workers. If supported, the code registers the service worker and determines if the page is actively controlled by the service worker. If it isn't, it prompts the user to reload the page so the service worker can take control. The code also reports any registration failures.

+ +
if ('serviceWorker' in navigator) {
+  // Register a service worker hosted at the root of the
+  // site using the default scope.
+  navigator.serviceWorker.register('/sw.js').then(function(registration) {
+    console.log('Service worker registration succeeded:', registration);
+
+    // At this point, you can optionally do something
+    // with registration. See https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerRegistration
+  }).catch(function(error) {
+    console.log('Service worker registration failed:', error);
+  });
+
+  // Independent of the registration, let's also display
+  // information about whether the current page is controlled
+  // by an existing service worker, and when that
+  // controller changes.
+
+  // First, do a one-off check if there's currently a
+  // service worker in control.
+  if (navigator.serviceWorker.controller) {
+    console.log('This page is currently controlled by:', navigator.serviceWorker.controller);
+  }
+
+  // Then, register a handler to detect when a new or
+  // updated service worker takes control.
+  navigator.serviceWorker.oncontrollerchange = function() {
+    console.log('This page is now controlled by:', navigator.serviceWorker.controller);
+  };
+} else {
+  console.log('Service workers are not supported.');
+}
+ +

Specifications

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

Browser compatibility

+ +
+ + +

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

+
+ +

See also

+ + diff --git a/files/id/web/api/serviceworkerregistration/index.html b/files/id/web/api/serviceworkerregistration/index.html new file mode 100644 index 0000000000..6ce1b3c033 --- /dev/null +++ b/files/id/web/api/serviceworkerregistration/index.html @@ -0,0 +1,245 @@ +--- +title: ServiceWorkerRegistration +slug: Web/API/ServiceWorkerRegistration +tags: + - API + - Draft + - Interface + - NeedsTranslation + - Offline + - Reference + - Service Workers + - ServiceWorkerRegistration + - TopicStub + - Workers +translation_of: Web/API/ServiceWorkerRegistration +--- +
+
{{SeeCompatTable}}{{APIRef("Service Workers API")}}
+
+ +

The ServiceWorkerRegistration interface of the ServiceWorker API represents the service worker registration. You register a service worker to control one or more pages that share the same origin.

+ +

The lifetime of a service worker registration is beyond that of the ServiceWorkerRegistration objects that represent them within the lifetime of their corresponding service worker clients. The browser maintains a persistent list of active ServiceWorkerRegistration objects.

+ +
+

Note: This feature is available in Web Workers.

+
+ +

Properties

+ +

Also implements properties from its parent interface, {{domxref("EventTarget")}}.

+ +
+
{{domxref("ServiceWorkerRegistration.scope")}} {{readonlyinline}}
+
Returns a unique identifier for a service worker registration. This must be on the same origin as the document that registers the {{domxref("ServiceWorker")}}.
+
{{domxref("ServiceWorkerRegistration.installing")}} {{readonlyinline}}
+
Returns a service worker whose state is installing. This is initially set to null.
+
{{domxref("ServiceWorkerRegistration.waiting")}} {{readonlyinline}}
+
Returns a service worker whose state is installed. This is initially set to null.
+
{{domxref("ServiceWorkerRegistration.active")}} {{readonlyinline}}
+
Returns a service worker whose state is either activating or activated. This is initially set to null. An active worker will control a {{domxref("ServiceWorkerClient")}} if the client's URL falls within the scope of the registration (the scope option set when {{domxref("ServiceWorkerContainer.register")}} is first called.)
+
{{domxref("serviceWorkerRegistration.periodicSync")}} {{non-standard_inline}} {{readonlyinline}}
+
Returns a reference to the {{domxref("PeriodicSyncManager")}} interface, which manages periodic background synchronization processes.
+
{{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.
+
{{domxref("ServiceWorkerRegistration.sync")}} {{non-standard_inline}} {{readonlyinline}} 
+
Returns a reference to the {{domxref("SyncManager")}} interface, which manages background synchronization processes.
+
+ +

Event handlers

+ +
+
{{domxref("ServiceWorkerRegistration.onupdatefound")}} {{readonlyinline}}
+
An EventListener property called whenever an event of type updatefound is fired; it is fired any time the {{domxref("ServiceWorkerRegistration.installing")}} property acquires a new service worker.
+
+ +

Methods

+ +

Also implements methods from its parent interface, {{domxref("EventTarget")}}.

+ +
+
{{domxref("ServiceWorkerRegistration.getNotifications()")}}
+
Returns a {{jsxref("Promise")}} that resolves to an array of {{domxref("Notification")}} objects.
+
{{domxref("ServiceWorkerRegistration.showNotification()")}}
+
Displays the notification with the requested title.
+
{{domxref("ServiceWorkerRegistration.update()")}}
+
Checks the server for an updated version of the service worker without consulting caches.
+
{{domxref("ServiceWorkerRegistration.unregister()")}}
+
Unregisters the service worker registration and returns a promise (see {{jsxref("Promise")}}). The service worker will finish any ongoing operations before it is unregistered.
+
+ +

Examples

+ +

This code snippet is from the service worker registration-events sample (live demo). The code checks to see if the browser supports service workers and if there's currently a service worker handling requests on this page for the current navigation.

+ +

Any new service workers are registered; if there's an existing service worker, the code overrides its default scope so that the registration applies to the current directory and everything underneath it. The example also reports any registration failures.

+ +
if ('serviceWorker' in navigator) {
+  document.querySelector('#availability').innerText = 'are';
+  document.querySelector('#controlled').innerText = navigator.serviceWorker.controller ? 'is' : 'is not';
+  navigator.serviceWorker.register('service-worker.js', {scope: './'}).then(function(registration) {
+    document.querySelector('#register').textContent = 'succeeded';
+  }).catch(function(error) {
+    document.querySelector('#register').textContent = 'failed: ' + error;
+  });
+} else {
+  document.querySelector('#availability').innerText = 'are not';
+}
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Service Workers', '#service-worker-registration-obj', 'ServiceWorkerRegistration')}}{{Spec2('Service Workers')}}Initial definition.
{{SpecName('Push API', '#widl-ServiceWorkerRegistration-pushManager', 'PushManager')}}{{Spec2('Push API')}}Adds the {{domxref("PushManager","pushManager")}} property.
{{SpecName('Web Notifications')}}{{Spec2('Web Notifications')}}Adds the {{domxref("ServiceWorkerRegistration.showNotification()","showNotification()")}} method and the {{domxref("ServiceWorkerRegistration.getNotifications()","getNotifications()")}} method.
{{SpecName('Background Sync')}}{{Spec2('Background Sync')}}Adds the {{domxref("ServiceWorkerRegistration.sync","sync")}} property.
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(40.0)}}{{ CompatGeckoDesktop("44.0") }}[1]{{CompatNo}}{{CompatUnknown}}{{CompatNo}}
Available in web workers{{CompatVersionUnknown}}{{CompatGeckoDesktop("44.0")}}[1]{{CompatNo}}{{CompatUnknown}}{{CompatNo}}
getNotifications(), showNotification(){{CompatVersionUnknown}}{{CompatGeckoDesktop("46.0")}}[1]{{CompatNo}}{{CompatUnknown}}{{CompatNo}}
sync property{{CompatChrome(49.0)}}    
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatNo}}{{ CompatGeckoMobile("44.0") }}{{ CompatVersionUnknown }}{{CompatNo}}{{CompatUnknown}}{{CompatNo}}{{CompatChrome(40.0)}}
Available in web workers{{CompatNo}}{{CompatNo}}{{CompatGeckoMobile("44.0")}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatUnknown}}{{CompatNo}}{{CompatVersionUnknown}}
getNotifications(), showNotification(){{CompatNo}}{{CompatNo}}{{CompatGeckoMobile("46.0")}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatUnknown}}{{CompatNo}}{{CompatVersionUnknown}}
sync property{{CompatNo}}{{CompatNo}}     {{CompatChrome(49.0)}}
+
+ +

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

+ +

See also

+ + diff --git a/files/id/web/api/serviceworkerregistration/pushmanager/index.html b/files/id/web/api/serviceworkerregistration/pushmanager/index.html new file mode 100644 index 0000000000..57f61c1375 --- /dev/null +++ b/files/id/web/api/serviceworkerregistration/pushmanager/index.html @@ -0,0 +1,130 @@ +--- +title: ServiceWorkerRegistration.pushManager +slug: Web/API/ServiceWorkerRegistration/pushManager +tags: + - API + - Property + - Push + - PushManager + - ServiceWorker +translation_of: Web/API/ServiceWorkerRegistration/pushManager +--- +
{{SeeCompatTable}}{{APIRef("Service Workers API")}}
+ +

Properti pushManager dari interface {{domxref("ServiceWorkerRegistration")}}  Mengembalikan sebuah referensi ke Interface {{domxref("PushManager")}} untuk mengatur push subscriptions; termasuk dukungan untuk berlangganan, mendapatkan langganan yang aktif, dan mengakses izin status push.

+ +

Sintaks

+ +
myPushManager = ServiceWorker.pushManager
+
+ +

Value

+ +

Objek {{domxref("PushManager")}}.

+ +

Contoh

+ +
this.onpush = function(event) {
+  console.log(event.data);
+  // Dari sini kita bisa menyimpan data ke IndexedDB, mengirimnya ke setiap
+  // jendela yang terbuka, menampilkan notifikasi, dsb.
+}
+
+navigator.serviceWorker.register('serviceworker.js').then(
+  function(serviceWorkerRegistration) {
+    serviceWorkerRegistration.pushManager.subscribe().then(
+      function(pushSubscription) {
+        console.log(pushSubscription.subscriptionId);
+        console.log(pushSubscription.endpoint);
+        // Detail langganan push dibutuhkan aplikasi
+        // server kini tersedia, dan dapat di kirimkan menggunakan,
+        // XMLHttpRequest misalnya.
+      }, function(error) {
+        // Pada saat pengembangan menampilkan log ke konsole sangatlah membantu
+        // Di lingkungan produksi juga dapat bermanfaat untuk mengirimkan
+        // informasi error kembali ke aplikasi server.
+        console.log(error);
+      }
+    );
+  });
+ +

Spesifikasi

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Push API', '#pushmanager-interface', 'PushManager')}}{{Spec2('Push API')}}Initial definition.
+ +

Kompabilitas Browser

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(42.0)}}{{ CompatGeckoDesktop("44.0") }}[1]{{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)}}
+
+ +

[1] Service workers (dan Push) telah dinonaktifkan di Firefox 45 Extended Support Release (ESR.)

+ +

Lihat Juga

+ + diff --git a/files/id/web/api/speechsynthesis/index.html b/files/id/web/api/speechsynthesis/index.html new file mode 100644 index 0000000000..78a50f3f47 --- /dev/null +++ b/files/id/web/api/speechsynthesis/index.html @@ -0,0 +1,151 @@ +--- +title: SpeechSynthesis +slug: Web/API/SpeechSynthesis +tags: + - API + - Experimental + - Interface + - NeedsTranslation + - Reference + - SpeechSynthesis + - TopicStub + - Web Speech API + - speech + - synthesis +translation_of: Web/API/SpeechSynthesis +--- +

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

+ +

The SpeechSynthesis interface of the Web Speech API is the controller interface for the speech service; this can be used to retrieve information about the synthesis voices available on the device, start and pause speech, and other commands besides.

+ +

Properties

+ +

SpeechSynthesis also inherits properties from its parent interface, {{domxref("EventTarget")}}.

+ +
+
{{domxref("SpeechSynthesis.paused")}} {{readonlyinline}}
+
A {{domxref("Boolean")}} that returns true if the SpeechSynthesis object is in a paused state.
+
{{domxref("SpeechSynthesis.pending")}} {{readonlyinline}}
+
A {{domxref("Boolean")}} that returns true if the utterance queue contains as-yet-unspoken utterances.
+
{{domxref("SpeechSynthesis.speaking")}} {{readonlyinline}}
+
A {{domxref("Boolean")}} that returns true if an utterance is currently in the process of being spoken — even if SpeechSynthesis is in a paused state.
+
+ +
+
+ +

Methods

+ +

SpeechSynthesis also inherits methods from its parent interface, {{domxref("EventTarget")}}.

+ +
+
{{domxref("SpeechSynthesis.cancel()")}}
+
Removes all utterances from the utterance queue.
+
{{domxref("SpeechSynthesis.getVoices()")}}
+
Returns a list of {{domxref("SpeechSynthesisVoice")}} objects representing all the available voices on the current device.
+
{{domxref("SpeechSynthesis.pause()")}}
+
Puts the SpeechSynthesis object into a paused state.
+
{{domxref("SpeechSynthesis.resume()")}}
+
Puts the SpeechSynthesis object into a non-paused state: resumes it if it was already paused.
+
{{domxref("SpeechSynthesis.speak()")}}
+
Adds an {{domxref("SpeechSynthesisUtterance", "utterance")}} to the utterance queue; it will be spoken when any other utterances queued before it have been spoken.
+
+ +

Events

+ +

Listen to this event using addEventListener() or by assigning an event listener to the oneventname property of this interface.

+ +
+
voiceschanged
+
Fired when the list of {{domxref("SpeechSynthesisVoice")}} objects that would be returned by the {{domxref("SpeechSynthesis.getVoices()")}} method has changed.
+ Also available via the onvoiceschanged property.
+
+ +

Examples

+ +

In our basic Speech synthesiser demo, we first grab a reference to the SpeechSynthesis controller using window.speechSynthesis. After defining some necessary variables, we retrieve a list of the voices available using {{domxref("SpeechSynthesis.getVoices()")}} and populate a select menu with them so the user can choose what voice they want.

+ +

Inside the inputForm.onsubmit handler, we stop the form submitting with preventDefault(),  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();
+}
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Speech API', '#tts-section', 'SpeechSynthesis')}}{{Spec2('Web Speech API')}} 
+ +

Browser compatibility

+ +
+ + +

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

+
+ +

See also

+ + diff --git a/files/id/web/api/speechsynthesis/onvoiceschanged/index.html b/files/id/web/api/speechsynthesis/onvoiceschanged/index.html new file mode 100644 index 0000000000..3a5a3f799c --- /dev/null +++ b/files/id/web/api/speechsynthesis/onvoiceschanged/index.html @@ -0,0 +1,74 @@ +--- +title: Kk +slug: Web/API/SpeechSynthesis/onvoiceschanged +translation_of: Web/API/SpeechSynthesis/onvoiceschanged +--- +
{{APIRef("Web Speech API")}}{{SeeCompatTable}}
+ +

The onvoiceschanged property of the {{domxref("SpeechSynthesis")}} interface represents an event handler that will run when the list of {{domxref("SpeechSynthesisVoice")}} objects that would be returned by the {{domxref("SpeechSynthesis.getVoices()")}} method has changed (when the voiceschanged event fires.)

+ +

This may occur when speech synthesis is being done on the server-side and the voices list is being determined asynchronously, or when client-side voices are installed/uninstalled while a speech synthesis application is running.

+ +

Syntax

+ +
speechSynthesisInstance.onvoiceschanged = function() { ... };
+
+ +

Examples

+ +

This could be used to populate a list of voices that the user can choose between when the event fires (see our Speak easy synthesis demo.) Note that Firefox doesn't support it at present, and will just return a list of voices when {{domxref("SpeechSynthesis.getVoices()")}} is fired. With Chrome however, you have to wait for the event to fire before populating the list, hence the bottom if statement seen below.

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

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Speech API', '#dom-speechsynthesis-onvoiceschanged', 'onvoiceschanged')}}{{Spec2('Web Speech API')}}
+ +

Browser compatibility

+ +
+ + +

{{Compat("api.SpeechSynthesis.onvoiceschanged")}}

+
+ +

See also

+ + diff --git a/files/id/web/api/storage/index.html b/files/id/web/api/storage/index.html new file mode 100644 index 0000000000..2231fe2bd8 --- /dev/null +++ b/files/id/web/api/storage/index.html @@ -0,0 +1,100 @@ +--- +title: Storage +slug: Web/API/Storage +translation_of: Web/API/Storage +--- +
{{APIRef("Web Storage API")}}
+ +

The Storage interface of the Web Storage API provides access to a particular domain's session or local storage. It allows, for example, the addition, modification, or deletion of stored data items.

+ +

To manipulate, for instance, the session storage for a domain, a call to {{domxref("Window.sessionStorage")}} is made; whereas for local storage the call is made to {{domxref("Window.localStorage")}}.

+ +

Properties

+ +
+
{{domxref("Storage.length")}} {{readonlyInline}}
+
Returns an integer representing the number of data items stored in the Storage object.
+
+ +

Methods

+ +
+
{{domxref("Storage.key()")}}
+
When passed a number n, this method will return the name of the nth key in the storage.
+
+ +
+
{{domxref("Storage.getItem()")}}
+
When passed a key name, will return that key's value.
+
{{domxref("Storage.setItem()")}}
+
When passed a key name and value, will add that key to the storage, or update that key's value if it already exists.
+
{{domxref("Storage.removeItem()")}}
+
When passed a key name, will remove that key from the storage.
+
{{domxref("Storage.clear()")}}
+
When invoked, will empty all keys out of the storage.
+
+ +

Examples

+ +

Here we access a Storage object by calling localStorage. We first test whether the local storage contains data items using !localStorage.getItem('bgcolor'). If it does, we run a function called setStyles() that grabs the data items using {{domxref("Storage.getItem()")}} and uses those values to update page styles. If it doesn't, we run another function, populateStorage(), which uses {{domxref("Storage.setItem()")}} to set the item values, then runs setStyles().

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

Note: To see this running as a complete working example, see our Web Storage Demo.

+
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'webstorage.html#the-storage-interface', 'Storage')}}{{Spec2('HTML WHATWG')}} 
+ +

Browser compatibility

+ + + +

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

+ +

See also

+ + diff --git a/files/id/web/api/webgl_api/index.html b/files/id/web/api/webgl_api/index.html new file mode 100644 index 0000000000..3450359705 --- /dev/null +++ b/files/id/web/api/webgl_api/index.html @@ -0,0 +1,235 @@ +--- +title: WebGL +slug: Web/API/WebGL_API +tags: + - Referensi + - WebGL +translation_of: Web/API/WebGL_API +--- +
{{WebGLSidebar}}
+ +
+

WebGL (Web Graphics Library) merupakan JavaScript API untuk merender grafik interaktif dalam bentuk 3D dan 2D pada setiap web browser yang kompitable tanpa menggunakan plug-in. WebGL juga memperkenalkan sebuah API yang berkaitan erat dengan OpenGL ES 2.0 yang dapat digunakan di elemen {{HTMLElement("canvas")}} HTML5.

+
+ +

Dukungan WebGL telah tersedia di Firefox 4+, Google Chrome 9+, Opera 12+, Safari 5.1+ dan Internet Explorer 11+; namum, perangkat pengguna juga harus memiliki perangkat keras yang mendukung fitur ini.

+ +

Elemen {{HTMLElement("canvas")}} juga digunakan oleh Canvas 2D untuk menggambar grafik 2D pada halaman web.

+ +

Referensi

+ +

Standar Antarmuka

+ +
+ +
+ +

Ekstensi

+ +
+ +
+ +

Event

+ + + +

Tipe dan konstanta

+ + + +

Paduan dan tutorial

+ + + +

Tutorial lanjutan

+ + + +

Sumber

+ + + +

Pustaka

+ + + +

Spesifikasi

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpesifikasiStatusComment
{{SpecName('WebGL')}}{{Spec2('WebGL')}}Initial definition. Based on OpenGL ES 2.0
{{SpecName('WebGL2')}}{{Spec2('WebGL2')}}Builds on top of WebGL1. Based on OpenGL ES 3.0.
{{SpecName('OpenGL ES 2.0')}}{{Spec2('OpenGL ES 2.0')}} 
{{SpecName('OpenGL ES 3.0')}}{{Spec2('OpenGL ES 3.0')}} 
+ +

Kompabilitas browser

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureFirefox (Gecko)ChromeInternet ExplorerOperaSafari
Basic support{{CompatGeckoDesktop("2.0")}}91112[1]5.1[1]
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureFirefox Mobile (Gecko)Chrome for AndroidIE MobileOpera MobileSafari Mobile
Basic support425[1]{{CompatNo}}12[1]8.1
+
+ +

[1]  Implementasi dari fitur ini adalah eksperimental.

+ +

Catatan kompabilitas

+ +

Selain browser, GPU sendiri juga dibutuhkan untuk mendukung fitur ini. Contohnya, S3 Texture Compression (S3TC) hanya tersedia di tablet berbasis Tegra. Hampir setiap browser membuat konteks WebGL tersedia dari nama konteks webgl, tapi untuk yang lebih lama juga memerlukan experimental-webgl. Selain itu , nantinya WebGL 2 sepenuhnya kompitable dengan yang sebelumnya dan akan memiliki nama konteks webgl2.

+ +

Catatan Gecko

+ +

Pengujian dan debungging WebGL

+ +

Dimulai dari Gecko 10.0 {{geckoRelease("10.0")}}, disana tersedia dua pengaturan yang memungkinkan anda mengontrol kemampuan WebGL untuk keperluan percobaan:

+ +
+
webgl.min_capability_mode
+
Properti Boolean yang, jika true, mengaktifkan mode kemampuan minimum. Pada mode ini, WebGL hanya diatur untuk mendukung fitur pengaturan minimum dan kemampuan yang dibutuhkan oleh spesifikasi WebGL. Memungkinkan anda untuk memastikan bahwa kode WebGL anda akan bekerja untuk setiap perangkat atau browser, tergantung dari kemampuan mereka. Nilai defaultnya adalah false.
+
webgl.disable_extensions
+
Properti Boolean yang, jika true, menonaktifkan semua ekstensi WebGL. Nilai defaultnya false.
+
+ +

Lihat Juga

+ + diff --git a/files/id/web/api/webrtc_api/index.html b/files/id/web/api/webrtc_api/index.html new file mode 100644 index 0000000000..6d9aa7392c --- /dev/null +++ b/files/id/web/api/webrtc_api/index.html @@ -0,0 +1,185 @@ +--- +title: WebRTC API +slug: Web/API/WebRTC_API +translation_of: Web/API/WebRTC_API +--- +
{{APIRef("WebRTC")}}
+ +

WebRTC (Web Real-Time Communications) merupakan teknologi yang memungkinkan situs dan aplikasi berbasis web menangkap dan mengirimkan audio atau video, serta bertukar data antar peramban web tanpa memerlukan adanya perantara. Kumpulan standar di dalam WebRTC membuat pertukaran data dan telekonferensi secara peer-to-peer dapat terjadi tanpa perlu memasang plugins atau aplikasi pihak ketiga.

+ +

WebRTC terdiri dari berbagai API dan protokol yang saling terkait sehingga dapat bekerja sebagaimana mestinya. Dokumentasi ini akan membantu anda untuk memahami dasar-dasar WebRTC, bagaimana mengatur dan menggunakan sambungan data dan media, serta hal lainnya.

+ +

Konsep dan cara penggunaan WebRTC

+ +

WebRTC memiliki beberapa fungsi, begitu halnya juga dengan Media Capture and Streams ({{domxref("MediaDevices")}}) API. Keduanya menghadirkan kemampuan multimedia di dalam web, misalnya audio dan video conferencing, pertukaran file, identity management, serta interaksi pada jaringan telepon dengan cara mengirimkan sinyal {{Glossary("DTMF")}}. Sambungan antar peer dapat terbentuk tanpa plugins tambahan, dan sering kali dapat terbentuk tanpa memerlukan server perantara.

+ +

Sambungan antar peer dibuat menggunakan - dan direpresentasikan oleh - {{domxref("RTCPeerConnection")}}. Ketika sebuah sambungan telah terbentuk dan terbuka, stream media ({{domxref("MediaStream")}}) atau channel data ({{domxref("RTCDataChannel")}}) dapat ditambahkan ke dalam sambungan peer.

+ +

Stream media terdiri dari beberapa track media, yang direpresentasikan oleh sebuah objek {{domxref("MediaStreamTrack")}}, yang berisi salah satu tipe media, yaitu audio, video, dan teks (misalnya subtitle atau nama judul). Umumnya stream terdiri dari setidaknya satu track audio bahkan juga satu track video, dan dapat digunakan untuk mengirim dan menerima media secara live atau dapat berupa rekaman media (misalnya streaming film).

+ +

Anda juga dapat menggunakan sambungan antar peer untuk bertukar sembarang data biner menggunakan {{domxref("RTCDataChannel")}}. Sambungan ini dapat digunakan untuk informasi back-channel, metadatagamingfile transfer, bahkan sebagai jalur utama pertukaran data.

+ +

artikel ini memerlukan informasi yang lebih lanjut serta tautan untuk panduan dan tutorial yang relevan

+ +

WebRTC interfaces

+ +

Because WebRTC provides interfaces that work together to accomplish a variety of tasks, we have divided up the interfaces in the list below by category. Please see the sidebar for an alphabetical list.

+ +

Connection setup and management

+ +

These interfaces are used to set up, open, and manage WebRTC connections.

+ +
+
{{domxref("RTCPeerConnection")}}
+
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.
+
{{domxref("RTCDataChannel")}}
+
Represents a bi-directional data channel between two peers of a connection.
+
{{domxref("RTCDataChannelEvent")}}
+
Represents events that occur while attaching a {{domxref("RTCDataChannel")}} to a {{domxref("RTCPeerConnection")}}. The only event sent with this interface is {{event("datachannel")}}.
+
{{domxref("RTCSessionDescription")}}
+
Represents the parameters of a session. Each RTCSessionDescription consists of a description type indicating which part of the offer/answer negotiation process it describes and of the SDP descriptor of the session.
+
{{domxref("RTCStatsReport")}}
+
Provides information detailing statistics for a connection or for an individual track on the connection; the report can be obtained by calling {{domxref("RTCPeerConnection.getStats()")}}.
+
{{domxref("RTCIceCandidate")}}
+
Represents a candidate internet connectivity establishment (ICE) server for establishing an {{domxref("RTCPeerConnection")}}.
+
{{domxref("RTCIceTransport")}}
+
Represents information about an internet connectivity establishment (ICE) transport.
+
{{domxref("RTCPeerConnectionIceEvent")}}
+
Represents events that occurs in relation to ICE candidates with the target, usually an {{domxref("RTCPeerConnection")}}. Only one event is of this type: {{event("icecandidate")}}.
+
{{domxref("RTCRtpSender")}}
+
Manages the encoding and transmission of data for a {{domxref("MediaStreamTrack")}} on an {{domxref("RTCPeerConnection")}}.
+
{{domxref("RTCRtpReceiver")}}
+
Manages the reception and decoding of data for a {{domxref("MediaStreamTrack")}} on an {{domxref("RTCPeerConnection")}}.
+
{{domxref("RTCTrackEvent")}}
+
Indicates that a new incoming {{domxref("MediaStreamTrack")}} was created and an associated {{domxref("RTCRtpReceiver")}} object was added to the {{domxref("RTCPeerConnection")}} object.
+
+ +

Identity and security

+ +

The WebRTC API includes a number of interfaces to manage security and identity.

+ +
+
{{domxref("RTCIdentityProvider")}}
+
Enables a user agent is able to request that an identity assertion be generated or validated.
+
{{domxref("RTCIdentityAssertion")}}
+
Represents the identity of the a remote peer of the current connection. If no peer has yet been set and verified this interface returns null. Once set it can't be changed.
+
{{domxref("RTCIdentityProviderRegistrar")}}
+
Registers an  identity provider (idP).
+
{{domxref("RTCIdentityEvent")}}
+
Represents an identity assertion generated by an identity provider (idP). This is usually for an {{domxref("RTCPeerConnection")}}. The only event sent with this type is {{event("identityresult")}}.
+
{{domxref("RTCIdentityErrorEvent")}}
+
Represents an error associated with the identity provider (idP). This is usually for an {{domxref("RTCPeerConnection")}}. Two events are sent with this type: {{event("idpassertionerror")}} and {{event("idpvalidationerror")}}.
+
{{domxref("RTCCertificate")}}
+
Represents a certificate that an {{domxref("RTCPeerConnection")}} uses to authenticate.
+
+ +

Telephony

+ +

These interfaces are related to interactivity with public-switched telephone networks (PTSNs).

+ +
+
{{domxref("RTCDTMFSender")}}
+
Manages the encoding and transmission of dual-tone multi-frequency (DTMF) signaling for an {{domxref("RTCPeerConnection")}}.
+
{{domxref("RTCDTMFToneChangeEvent")}}
+
Indicates an occurrence of a of dual-tone multi-frequency (DTMF). This event does not bubble (except where otherwise stated) and is not cancelable (except where otherwise stated).
+
+ +

Guides

+ +
+
Introduction to WebRTC protocols
+
This article introduces the protocols on top of which the WebRTC API is built.
+
WebRTC connectivity
+
A guide to how WebRTC connections work and how the various protocols and interfaces can be used together to build powerful communication apps.
+
Lifetime of a WebRTC session
+
WebRTC lets you build peer-to-peer communication of arbitrary data, audio, or video—or any combination thereof—into a browser application. In this article, we'll look at the lifetime of a WebRTC session, from establishing the connection all the way through closing the connection when it's no longer needed.
+
Signaling and two-way video calling
+
A tutorial and example which turbs a WebSocket-based chat system created for a previous example and adds support for opening video calls among participants. The chat server's WebSocket connection is used for WebRTC signaling.
+
Using WebRTC data channels
+
This guide covers how you can use a peer connection and an associated {{domxref("RTCDataChannel")}} to exchange arbitrary data between two peers.
+
Using DTMF with WebRTC
+
WebRTC's support for interacting with gateways that link to old-school telephone systems includes support for sending DTMF tones using the {{domxref("RTCDTMFSender")}} interface. This guide shows how to do so.
+
+ +

Tutorials

+ +
+
Improving compatibility using WebRTC adapter.js
+
The WebRTC organization provides on GitHub the WebRTC adapter to work around compatibility issues in different browsers' WebRTC implementations. The adapter is a JavaScript shim which lets your code to be written to the specification so that it will "just work" in all browsers with WebRTC support.
+
Taking still photos with WebRTC
+
This article shows how to use WebRTC to access the camera on a computer or mobile phone with WebRTC support and take a photo with it.
+
A simple RTCDataChannel sample
+
The {{domxref("RTCDataChannel")}} interface is a feature which lets you open a channel between two peers over which you may send and receive arbitrary data. The API is intentionally similar to the WebSocket API, so that the same programming model can be used for each.
+
+ +

Resources

+ +

Protocols

+ +

WebRTC-proper protocols

+ + + + + + + +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WebRTC 1.0')}}{{Spec2('WebRTC 1.0')}}The initial definition of the API of WebRTC.
{{SpecName('Media Capture')}}{{Spec2('Media Capture')}}The initial definition of the object conveying the stream of media content.
{{SpecName('Media Capture DOM Elements')}}{{Spec2('Media Capture DOM Elements')}}The initial definition on how to obtain stream of content from DOM Elements
+ +

In additions to these specifications defining the API needed to use WebRTC, there are several protocols, listed under resources.

+ + + + diff --git a/files/id/web/api/window/getselection/index.html b/files/id/web/api/window/getselection/index.html new file mode 100644 index 0000000000..274aa85b2d --- /dev/null +++ b/files/id/web/api/window/getselection/index.html @@ -0,0 +1,100 @@ +--- +title: Window.getSelection() +slug: Web/API/Window/getSelection +tags: + - API + - API Pilihan + - DOM + - Metode + - Pilihan + - Refrensi + - Window +translation_of: Web/API/Window/getSelection +--- +
{{ ApiRef() }}
+ +

Window.getSelection() adalah metode {{domxref("Selection")}} yang menggambarkan teks yang ditandai oleh pengguna atau posisi sekarang.

+ +

Syntak

+ +
selection = window.getSelection();
+ +

Hasil Output

+ +

Objek {{domxref("Selection")}}

+ +

Ketika berganti ke string, lebih baik menggunakan string kosong ("") atau menggunakan {{domxref("Selection.toString()")}}, hasil output adalah teks yang dipilih.

+ +

Ketika memanggil sebuah {{htmlelement("iframe")}} ini tidak akan ditampilkan (misalnya display: none telah diatur) Firefox akan menampilkan null, sedangkan browser lain akan menampilkan objek {{domxref("Selection")}} dengan {{domxref("Selection.type")}} yang diatur ke None.

+ +

Contoh

+ +
function foo() {
+    var selObj = window.getSelection();
+    alert(selObj);
+    var selRange = selObj.getRangeAt(0);
+    // do stuff with the range
+}
+ +

Catatan

+ +

Representasi dari objek Selection

+ +

Dalam JavaScript, ketika sebuah objek dimasukan ke function yang membutuhkan string (seperti {{ Domxref("window.alert()") }} atau {{ Domxref("document.write()") }}), objek metode {{jsxref("Object.toString", "toString()")}} akan dipanggil dan hasilnya akan dikembalikan ke function tersebut. Ini akan membuat objek dapat tampil sebagai string ketika digunakan oleh function lainnya ketika ini adalah objek dan metode yang benar.

+ +

Pada contoh berikut, selObj.toString() akan otomatis dipanggil ketika melewati {{domxref("window.alert()")}}. Bagaimanapun, mencoba menggunakan properti atau metode JavaScript String seperti length atau substr secara langsung pada objek {{domxref ("Selection")}} akan menghasilkan kesalahan jika tidak memiliki properti atau metode dan dapat mengembalikan hasil yang tidak terduga jika itu benar. Untuk menggunakan objek Selection sebagai string, panggil metode toString () secara langsung:

+ +
var selectedText = selObj.toString();
+ + + +

Objek terhubung

+ +

Kamu bisa memanggil {{domxref("Document.getSelection()")}}, yang mana ini bekerja seperti Window.getSelection().

+ +

Perlu diingat, bahwa saat ini getSelection() tidak bekerja pada elemen {{htmlelement("textarea")}} and {{htmlelement("input")}} di Firefox. Properti {{domxref("HTMLInputElement.setSelectionRange()")}} atau selectionStart dan selectionEnd yang dapat menangani hal ini.

+ +

Perhatikan juga perbedaan atara selection dan focus. {{domxref("Document.activeElement")}} menampilkan elemen yang sedang difokus.

+ +

Spesifikasi

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("Selection API", "#extensions-to-window-interface", "Window.getSelection()")}}{{Spec2("Selection API")}}New spec.
{{SpecName("HTML Editing", "#dom-window-getselection", "Window.getSelection()")}}{{Spec2("HTML Editing")}}Initial definition
+ +

Browser compatibility

+ + + +

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

+ +

See also

+ + diff --git a/files/id/web/api/window/index.html b/files/id/web/api/window/index.html new file mode 100644 index 0000000000..79736ccf64 --- /dev/null +++ b/files/id/web/api/window/index.html @@ -0,0 +1,479 @@ +--- +title: Window +slug: Web/API/Window +tags: + - API + - DOM + - Interface + - JavaScript + - NeedsTranslation + - Reference + - TopicStub + - Window +translation_of: Web/API/Window +--- +

{{APIRef}}

+ +

The window object represents a window containing a DOM document; the document property points to the DOM document loaded in that window. A window for a given document can be obtained using the {{Domxref("document.defaultView")}} property.

+ +

This section provides a brief reference for all of the methods, properties, and events available through the DOM window object. The window object implements the Window interface, which in turn inherits from the AbstractView interface. Some additional global functions, namespaces, objects, interfaces, and constructors, not typically associated with the window, but available on it, are listed in the JavaScript Reference and DOM Reference.

+ +

In a tabbed browser, such as Firefox, each tab contains its own window object (and if you're writing an extension, the browser window itself is a separate window too - see Working with windows in chrome code for more information). That is, the window object is not shared between tabs in the same window. Some methods, namely {{Domxref("window.resizeTo")}} and {{Domxref("window.resizeBy")}} apply to the whole window and not to the specific tab the window object belongs to. Generally, anything that can't reasonably pertain to a tab pertains to the window instead.

+ +

{{InheritanceDiagram}}

+ +

Properties

+ +

This interface inherits properties from the {{domxref("EventTarget")}} interface and implements properties from the {{domxref("WindowOrWorkerGlobalScope")}} and {{domxref("WindowEventHandlers")}} mixins.

+ +

Note that properties which are objects (e.g.,. for overriding the prototype of built-in elements) are listed in a separate section below.

+ +
+
{{domxref("Window.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.
+
{{domxref("Window.console")}} {{ReadOnlyInline}}
+
Returns a reference to the console object which provides access to the browser's debugging console.
+
{{domxref("Window.content")}} and Window._content {{Non-standard_inline}} {{obsolete_inline}}{{ReadOnlyInline}}
+
Returns a reference to the content element in the current window. Since Firefox 57 (initially Nightly-only), both versions are only available from chrome (privileged) code, and not available to the web anymore.
+
{{domxref("Window.controllers")}}{{non-standard_inline}}{{ReadOnlyInline}}
+
Returns the XUL controller objects for the current chrome window.
+
{{domxref("Window.crypto")}} {{readOnlyInline}}
+
Returns the browser crypto object.
+
{{domxref("Window.defaultStatus")}} {{Obsolete_inline("gecko23")}}
+
Gets/sets the status bar text for the given window.
+
{{domxref("Window.devicePixelRatio")}} {{non-standard_inline}}{{ReadOnlyInline}}
+
Returns the ratio between physical pixels and device independent pixels in the current display.
+
{{domxref("Window.dialogArguments")}} {{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")}} {{readOnlyInline}}
+
Gets the height of the content area of the browser window including, if rendered, the horizontal scrollbar.
+
{{domxref("Window.innerWidth")}} {{readOnlyInline}}
+
Gets the width of the content area of the browser window including, if rendered, the vertical scrollbar.
+
{{domxref("Window.isSecureContext")}} {{readOnlyInline}}
+
Indicates whether a context is capable of using features that require secure contexts.
+
{{domxref("Window.length")}} {{readOnlyInline}}
+
Returns the number of frames in the window. See also {{domxref("window.frames")}}.
+
{{domxref("Window.location")}}
+
Gets/sets the location, or current URL, of the window object.
+
{{domxref("Window.locationbar")}} {{ReadOnlyInline}}
+
Returns the locationbar object, whose visibility can be toggled in the window.
+
{{domxref("Window.localStorage")}} {{readOnlyInline}}{{gecko_minversion_inline("1.9.1")}}
+
Returns a reference to the local storage object used to store data that may only be accessed by the origin that created it.
+
{{domxref("Window.menubar")}} {{ReadOnlyInline}}
+
Returns the menubar object, whose visibility can be toggled in the window.
+
{{domxref("Window.messageManager")}} {{gecko_minversion_inline("2.0")}}
+
Returns the message manager object for this window.
+
{{domxref("Window.mozAnimationStartTime")}} {{ReadOnlyInline}}{{gecko_minversion_inline("2.0")}} {{Deprecated_inline}}
+
The time in milliseconds since epoch at which the current animation cycle began.
+
{{domxref("Window.mozInnerScreenX")}} {{ReadOnlyInline}}{{non-standard_inline}}{{gecko_minversion_inline("1.9.2")}}
+
Returns the horizontal (X) coordinate of the top-left corner of the window's viewport, in screen coordinates. This value is reported in CSS pixels. See mozScreenPixelsPerCSSPixel in {{interface("nsIDOMWindowUtils")}} for a conversion factor to adapt to screen pixels if needed.
+
{{domxref("Window.mozInnerScreenY")}} {{ReadOnlyInline}} {{non-standard_inline}}{{gecko_minversion_inline("1.9.2")}}
+
Returns the vertical (Y) coordinate of the top-left corner of the window's viewport, in screen coordinates. This value is reported in CSS pixels. See mozScreenPixelsPerCSSPixel for a conversion factor to adapt to screen pixels if needed.
+
{{domxref("Window.mozPaintCount")}} {{non-standard_inline}}{{ReadOnlyInline}} {{gecko_minversion_inline("2.0")}}
+
Returns the number of times the current document has been rendered to the screen in this window. This can be used to compute rendering performance.
+
{{domxref("Window.name")}}
+
Gets/sets the name of the window.
+
{{domxref("Window.navigator")}} {{readOnlyInline}}
+
Returns a reference to the navigator object.
+
{{domxref("Window.opener")}}
+
Returns a reference to the window that opened this current window.
+
{{domxref("Window.orientation")}}{{non-standard_inline}}{{deprecated_inline}}{{readOnlyInline}}
+
Returns the orientation in degrees (in 90 degree increments) of the viewport relative to the device's natural orientation.
+
{{domxref("Window.outerHeight")}} {{readOnlyInline}}
+
Gets the height of the outside of the browser window.
+
{{domxref("Window.outerWidth")}} {{readOnlyInline}}
+
Gets the width of the outside of the browser window.
+
{{domxref("Window.scrollX","Window.pageXOffset")}} {{readOnlyInline}}
+
An alias for {{domxref("window.scrollX")}}.
+
{{domxref("Window.scrollY","Window.pageYOffset")}}{{readOnlyInline}}
+
An alias for {{domxref("window.scrollY")}}
+
{{domxref("Window.sessionStorage")}} {{readOnlyInline}}
+
Returns a reference to the session storage object used to store data that may only be accessed by the origin that created it.
+
{{domxref("Window.parent")}} {{readOnlyInline}}
+
Returns a reference to the parent of the current window or subframe.
+
{{domxref("Window.performance")}} {{readOnlyInline}}
+
Returns a {{domxref("Performance")}} object, which includes the {{domxref("Performance.timing", "timing")}} and {{domxref("Performance.navigation", "navigation")}} attributes, each of which is an object providing performance-related data. See also Using Navigation Timing for additional information and examples.
+
{{domxref("Window.personalbar")}} {{readOnlyInline}}
+
Returns the personalbar object, whose visibility can be toggled in the window.
+
{{domxref("Window.pkcs11")}} {{obsolete_inline(29)}}
+
Formerly provided access to install and remove PKCS11 modules.
+
{{domxref("Window.returnValue")}} {{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.speechSynthesis")}} {{ReadOnlyInline}}
+
Returns a {{domxref("SpeechSynthesis")}} object, which is the entry point into using Web Speech API speech synthesis functionality.
+
{{domxref("Window.status")}}
+
Gets/sets the text in the statusbar at the bottom of the browser.
+
{{domxref("Window.statusbar")}} {{readOnlyInline}}
+
Returns the statusbar object, whose visibility can be toggled in the window.
+
{{domxref("Window.toolbar")}} {{readOnlyInline}}
+
Returns the toolbar object, whose visibility can be toggled in the window.
+
{{domxref("Window.top")}} {{readOnlyInline}}
+
Returns a reference to the topmost window in the window hierarchy. This property is read only.
+
{{domxref("Window.visualViewport")}} {{readOnlyInline}}
+
Returns a {{domxref("VisualViewport")}} object which represents the visual viewport for a given window.
+
{{domxref("Window.window")}} {{ReadOnlyInline}}
+
Returns a reference to the current window.
+
window[0], window[1], etc.
+
Returns a reference to the window object in the frames. See {{domxref("Window.frames")}} for more details.
+
+ +

Properties implemented from elsewhere

+ +
+
{{domxref("WindowOrWorkerGlobalScope.caches")}} {{readOnlyinline}}
+
Returns the {{domxref("CacheStorage")}} object associated with the current context. This object enables functionality such as storing assets for offline use, and generating custom responses to requests.
+
{{domxref("WindowOrWorkerGlobalScope.indexedDB")}} {{readonlyInline}}
+
Provides a mechanism for applications to asynchronously access capabilities of indexed databases; returns an {{domxref("IDBFactory")}} object.
+
{{domxref("WindowOrWorkerGlobalScope.isSecureContext")}} {{readOnlyinline}}
+
Returns a boolean indicating whether the current context is secure (true) or not (false).
+
{{domxref("WindowOrWorkerGlobalScope.origin")}} {{readOnlyinline}}
+
Returns the global object's origin, serialized as a string. (This does not yet appear to be implemented in any browser.)
+
+ +

Methods

+ +

This interface inherits methods from the {{domxref("EventTarget")}} interface and implements methods from {{domxref("WindowOrWorkerGlobalScope")}} and {{domxref("EventTarget")}}.

+ +
+
{{domxref("Window.alert()")}}
+
Displays an alert dialog.
+ +
{{domxref("Window.back()")}} {{Non-standard_inline}} {{obsolete_inline}}
+
Moves back one in the window history.
+
{{domxref("Window.blur()")}}
+
Sets focus away from the window.
+
{{domxref("Window.cancelAnimationFrame()")}} {{experimental_inline}}
+
Enables you to cancel a callback previously scheduled with {{domxref("Window.requestAnimationFrame")}}.
+
{{domxref("Window.cancelIdleCallback()")}} {{experimental_inline}}
+
Enables you to cancel a callback previously scheduled with {{domxref("Window.requestIdleCallback")}}.
+
{{domxref("Window.captureEvents()")}} {{Deprecated_inline}}
+
Registers the window to capture all events of the specified type.
+
{{domxref("Window.clearImmediate()")}}
+
Cancels the repeated execution set using setImmediate.
+
{{domxref("Window.close()")}}
+
Closes the current window.
+
{{domxref("Window.confirm()")}}
+
Displays a dialog with a message that the user needs to respond to.
+
{{domxref("Window.disableExternalCapture()")}} {{obsolete_inline(24)}}
+
{{todo("NeedsContents")}}
+
{{domxref("Window.dispatchEvent()")}}
+
Used to trigger an event.
+
{{domxref("Window.dump()")}} {{Non-standard_inline}}
+
Writes a message to the console.
+
{{domxref("Window.enableExternalCapture()")}} {{obsolete_inline(24)}}
+
{{todo("NeedsContents")}}
+
{{domxref("Window.find()")}}
+
Searches for a given string in a window.
+
{{domxref("Window.focus()")}}
+
Sets focus on the current window.
+
{{domxref("Window.forward()")}} {{Non-standard_inline}} {{obsolete_inline}}
+
Moves the window one document forward in the history.
+
{{domxref("Window.getAttention()")}} {{Non-standard_inline}} {{obsolete_inline}}
+
Flashes the application icon.
+
{{domxref("Window.getAttentionWithCycleCount()")}}
+
{{todo("NeedsContents")}}
+
{{domxref("Window.getComputedStyle()")}}
+
Gets computed style for the specified element. Computed style indicates the computed values of all CSS properties of the element.
+
{{domxref("Window.getDefaultComputedStyle()")}} {{Non-standard_inline}}
+
Gets default computed style for the specified element, ignoring author stylesheets.
+
{{domxref("Window.getSelection()")}}
+
Returns the selection object representing the selected item(s).
+
{{domxref("Window.home()")}} {{Non-standard_inline}} {{obsolete_inline}}
+
Returns the browser to the home page.
+
{{domxref("Window.matchMedia()")}} {{gecko_minversion_inline("6.0")}}
+
Returns a {{domxref("MediaQueryList")}} object representing the specified media query string.
+
{{domxref("Window.maximize()")}}
+
{{todo("NeedsContents")}}
+
{{domxref("Window.minimize()")}} (top-level XUL windows only)
+
Minimizes the window.
+
{{domxref("Window.moveBy()")}}
+
Moves the current window by a specified amount.
+
{{domxref("Window.moveTo()")}}
+
Moves the window to the specified coordinates.
+
{{domxref("Window.open()")}}
+
Opens a new window.
+
{{domxref("Window.openDialog()")}} {{Non-standard_inline}} {{obsolete_inline}}
+
Opens a new dialog window.
+
{{domxref("Window.postMessage()")}} {{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()")}} {{Non-standard_inline}} {{Deprecated_inline}}
+
Releases the window from trapping events of a specific type.
+
{{domxref("Window.requestAnimationFrame()")}} {{gecko_minversion_inline("2.0")}}
+
Tells the browser that an animation is in progress, requesting that the browser schedule a repaint of the window for the next animation frame.
+
{{domxref("Window.requestIdleCallback()")}}  {{experimental_inline}}
+
Enables the scheduling of tasks during a browser's idle periods.
+
{{domxref("Window.resizeBy()")}}
+
Resizes the current window by a certain amount.
+
{{domxref("Window.resizeTo()")}}
+
Dynamically resizes window.
+
{{domxref("Window.restore()")}} {{Non-standard_inline}} {{obsolete_inline}}
+
{{todo("NeedsContents")}}
+
{{domxref("Window.routeEvent()")}} {{obsolete_inline(24)}}
+
{{todo("NeedsContents")}}
+
{{domxref("Window.scroll()")}}
+
Scrolls the window to a particular place in the document.
+
{{domxref("Window.scrollBy()")}}
+
Scrolls the document in the window by the given amount.
+
{{domxref("Window.scrollByLines()")}} {{Non-standard_inline}}
+
Scrolls the document by the given number of lines.
+
{{domxref("Window.scrollByPages()")}} {{Non-standard_inline}}
+
Scrolls the current document by the specified number of pages.
+
{{domxref("Window.scrollTo()")}}
+
Scrolls to a particular set of coordinates in the document.
+
{{domxref("Window.setCursor()")}} {{Non-standard_inline}} (top-level XUL windows only)
+
Changes the cursor for the current window
+
{{domxref("Window.setImmediate()")}}
+
Executes a function after the browser has finished other heavy tasks
+
{{domxref("Window.setResizable()")}} {{Non-standard_inline}}
+
Toggles a user's ability to resize a window.
+
{{domxref("Window.sizeToContent()")}} {{Non-standard_inline}}
+
Sizes the window according to its content.
+
{{domxref("Window.stop()")}}
+
This method stops window loading.
+
{{domxref("Window.updateCommands()")}} {{Non-standard_inline}}
+
Updates the state of commands of the current chrome window (UI).
+
+ +

Methods implemented from elsewhere

+ +
+
{{domxref("EventTarget.addEventListener()")}}
+
Register an event handler to a specific event type on the window.
+
{{domxref("WindowOrWorkerGlobalScope.atob()")}}
+
Decodes a string of data which has been encoded using base-64 encoding.
+
{{domxref("WindowOrWorkerGlobalScope.btoa()")}}
+
Creates a base-64 encoded ASCII string from a string of binary data.
+
{{domxref("WindowOrWorkerGlobalScope.clearInterval()")}}
+
Cancels the repeated execution set using {{domxref("WindowOrWorkerGlobalScope.setInterval()")}}.
+
{{domxref("WindowOrWorkerGlobalScope.clearTimeout()")}}
+
Cancels the delayed execution set using {{domxref("WindowOrWorkerGlobalScope.setTimeout()")}}.
+
{{domxref("WindowOrWorkerGlobalScope.createImageBitmap()")}}
+
Accepts a variety of different image sources, and returns a {{domxref("Promise")}} which resolves to an {{domxref("ImageBitmap")}}. Optionally the source is cropped to the rectangle of pixels originating at (sx, sy) with width sw, and height sh.
+
{{domxref("WindowOrWorkerGlobalScope.fetch()")}}
+
Starts the process of fetching a resource from the network.
+
{{domxref("EventTarget.removeEventListener")}}
+
Removes an event listener from the window.
+
{{domxref("WindowOrWorkerGlobalScope.setInterval()")}}
+
Schedules a function to execute every time a given number of milliseconds elapses.
+
{{domxref("WindowOrWorkerGlobalScope.setTimeout()")}}
+
Schedules a function to execute in a given amount of time.
+
+ +

Obsolete methods

+ +
+
{{domxref("Window.showModalDialog()")}} {{obsolete_inline}}
+
Displays a modal dialog. This method was removed completely in Chrome 43, and Firefox 55.
+
+ +

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("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")}}
+
Called when the loading of a resource has been aborted, such as by a user canceling the load while it is still in progress
+
{{domxref("WindowEventHandlers.onafterprint")}}
+
Called when the print dialog box is closed. See {{event("afterprint")}} event.
+
{{domxref("WindowEventHandlers.onbeforeprint")}}
+
Called when the print dialog box is opened. See {{event("beforeprint")}} event.
+
{{domxref("Window.onbeforeinstallprompt")}}
+
An event handler property dispatched before a user is prompted to save a web site to a home screen on mobile.
+
{{domxref("WindowEventHandlers.onbeforeunload")}}
+
An event handler property for before-unload events on the window.
+
{{domxref("GlobalEventHandlers.onblur")}}
+
Called after the window loses focus, such as due to a popup.
+
{{domxref("GlobalEventHandlers.onchange")}}
+
An event handler property for change events on the window.
+
{{domxref("GlobalEventHandlers.onclick")}}
+
Called after the ANY mouse button is pressed & released
+
{{domxref("GlobalEventHandlers.ondblclick")}}
+
Called when a double click is made with ANY mouse button.
+
{{domxref("GlobalEventHandlers.onclose")}}
+
Called after the window is closed
+
{{domxref("GlobalEventHandlers.oncontextmenu")}}
+
Called when the RIGHT mouse button is pressed
+
{{domxref("Window.ondevicelight")}}
+
An event handler property for any ambient light levels changes
+
{{domxref("Window.ondevicemotion")}} {{gecko_minversion_inline("6.0")}}
+
Called if accelerometer detects a change (For mobile devices)
+
{{domxref("Window.ondeviceorientation")}} {{gecko_minversion_inline("6.0")}}
+
Called when the orientation is changed (For mobile devices)
+
{{domxref("Window.ondeviceorientationabsolute")}} {{non-standard_inline}} Chrome only
+
An event handler property for any device orientation changes.
+
{{domxref("Window.ondeviceproximity")}}
+
An event handler property for device proximity event
+
{{domxref("GlobalEventHandlers.onerror")}}
+
Called when a resource fails to load OR when an error occurs at runtime. See {{event("error")}} event.
+
{{domxref("GlobalEventHandlers.onfocus")}}
+
Called after the window receives or regains focus. See {{event("focus")}} events.
+
{{domxref("WindowEventHandlers.onhashchange")}} {{gecko_minversion_inline("1.9.2")}}
+
An event handler property for {{event('hashchange')}} events on the window; called when the part of the URL after the hash mark ("#") changes.
+
{{domxref("Window.onappinstalled")}}
+
Called when the page is installed as a webapp. See {{event('appinstalled')}} event.
+
{{domxref("Window.ongamepadconnected")}}
+
Represents an event handler that will run when a gamepad is connected (when the {{event('gamepadconnected')}} event fires).
+
{{domxref("Window.ongamepaddisconnected")}}
+
Represents an event handler that will run when a gamepad is disconnected (when the {{event('gamepaddisconnected')}} event fires).
+
{{domxref("Window.oninput")}}
+
Called when the value of an <input> element changes
+
{{domxref("GlobalEventHandlers.onkeydown")}}
+
Called when you begin pressing ANY key. See {{event("keydown")}} event.
+
{{domxref("GlobalEventHandlers.onkeypress")}}
+
Called when a key (except Shift, Fn, and CapsLock) is in pressed position. See {{event("keypress")}} event.
+
{{domxref("GlobalEventHandlers.onkeyup")}}
+
Called when you finish releasing ANY key. See {{event("keyup")}} event.
+
{{domxref("WindowEventHandlers.onlanguagechange")}}
+
An event handler property for {{event("languagechange")}} events on the window.
+
{{domxref("GlobalEventHandlers.onload")}}
+
Called after all resources and the DOM are fully loaded. WILL NOT get called when the page is loaded from cache, such as with back button.
+
{{domxref("WindowEventHandlers.onmessage")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("message")}} event is raised.
+
{{domxref("GlobalEventHandlers.onmousedown")}}
+
Called when ANY mouse button is pressed.
+
{{domxref("GlobalEventHandlers.onmousemove")}}
+
Called continously when the mouse is moved inside the window.
+
{{domxref("GlobalEventHandlers.onmouseout")}}
+
Called when the pointer leaves the window.
+
{{domxref("GlobalEventHandlers.onmouseover")}}
+
Called when the pointer enters the window
+
{{domxref("GlobalEventHandlers.onmouseup")}}
+
Called when ANY mouse button is released
+
{{domxref("Window.onmozbeforepaint")}} {{gecko_minversion_inline("2.0")}}
+
An event handler property for the MozBeforePaint event, which is sent before repainting the window if the event has been requested by a call to the {{domxref("Window.mozRequestAnimationFrame()")}} method.
+
{{domxref("WindowEventHandlers.onoffline")}}
+
Called when network connection is lost. See {{event("offline")}} event.
+
{{domxref("WindowEventHandlers.ononline")}}
+
Called when network connection is established. See {{event("online")}} event.
+
{{domxref("WindowEventHandlers.onpagehide")}}
+
Called when the user navigates away from the page, before the onunload event. See {{event("pagehide")}} event.
+
{{domxref("WindowEventHandlers.onpageshow")}}
+
Called after all resources and the DOM are fully loaded. See {{event("pageshow")}} event.
+
{{domxref("Window.onpaint")}}
+
An event handler property for paint events on the window.
+
{{domxref("WindowEventHandlers.onpopstate")}} {{gecko_minversion_inline("2.0")}}
+
Called when a back putton is pressed.
+
{{domxref("Window.onrejectionhandled")}} {{experimental_inline}}
+
An event handler for handled {{jsxref("Promise")}} rejection events.
+
{{domxref("GlobalEventHandlers.onreset")}}
+
Called when a form is reset
+
{{domxref("GlobalEventHandlers.onresize")}}
+
Called continuously as you are resizing the window.
+
{{domxref("GlobalEventHandlers.onscroll")}}
+
Called when the scroll bar is moved via ANY means. If the resource fully fits in the window, then this event cannot be invoked
+
{{domxref("GlobalEventHandlers.onwheel")}}
+
Called when the mouse wheel is rotated around any axis
+
{{domxref("GlobalEventHandlers.onselect")}}
+
Called after text in an input field is selected
+
{{domxref("GlobalEventHandlers.onselectionchange")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("selectionchange")}} event is raised.
+
{{domxref("WindowEventHandlers.onstorage")}}
+
Called when there is a change in session storage or local storage. See {{event("storage")}} event
+
{{domxref("GlobalEventHandlers.onsubmit")}}
+
Called when a form is submitted
+
{{domxref("WindowEventHandlers.onunhandledrejection")}} {{experimental_inline}}
+
An event handler for unhandled {{jsxref("Promise")}} rejection events.
+
{{domxref("WindowEventHandlers.onunload")}}
+
Called when the user navigates away from the page.
+
{{domxref("Window.onuserproximity")}}
+
An event handler property for user proximity events.
+
{{domxref("Window.onvrdisplayconnect")}}
+
Represents an event handler that will run when a compatible VR device has been connected to the computer (when the {{event("vrdisplayconnected")}} event fires).
+
{{domxref("Window.onvrdisplaydisconnect")}}
+
Represents an event handler that will run when a compatible VR device has been disconnected from the computer (when the {{event("vrdisplaydisconnected")}} event fires).
+
{{domxref("Window.onvrdisplayactivate")}}
+
Represents an event handler that will run when a display is able to be presented to (when the {{event("vrdisplayactivate")}} event fires), for example if an HMD has been moved to bring it out of standby, or woken up by being put on.
+
{{domxref("Window.onvrdisplaydeactivate")}}
+
Represents an event handler that will run when a display can no longer be presented to (when the {{event("vrdisplaydeactivate")}} event fires), for example if an HMD has gone into standby or sleep mode due to a period of inactivity.
+
{{domxref("Window.onvrdisplayblur")}}
+
Represents an event handler that will run when presentation to a display has been paused for some reason by the browser, OS, or VR hardware (when the {{event("vrdisplayblur")}} event fires) — for example, while the user is interacting with a system menu or browser, to prevent tracking or loss of experience.
+
{{domxref("Window.onvrdisplayfocus")}}
+
Represents an event handler that will run when presentation to a display has resumed after being blurred (when the {{event("vrdisplayfocus")}} event fires).
+
{{domxref("Window.onvrdisplaypresentchange")}}
+
represents an event handler that will run when the presenting state of a VR device changes — i.e. goes from presenting to not presenting, or vice versa (when the {{event("vrdisplaypresentchange")}} event fires).
+
+ +

Constructors

+ +

See also the DOM Interfaces.

+ +
+
{{domxref("DOMParser")}}
+
DOMParser can parse XML or HTML source stored in a string into a DOM DocumentDOMParser is specified in DOM Parsing and Serialization.
+
{{domxref("Window.GeckoActiveXObject")}}
+
{{todo("NeedsContents")}}
+
{{domxref("Image")}}
+
Used for creating an {{domxref("HTMLImageElement")}}.
+
{{domxref("Option")}}
+
Used for creating an {{domxref("HTMLOptionElement")}}
+
{{domxref("Window.QueryInterface")}}
+
{{todo("NeedsContents")}}
+
{{domxref("Window.XMLSerializer")}}
+
{{todo("NeedsContents")}}
+
{{domxref("Worker")}}
+
Used for creating a Web worker
+
{{domxref("Window.XPCNativeWrapper")}}
+
{{todo("NeedsContents")}}
+
{{domxref("Window.XPCSafeJSObjectWrapper")}}
+
{{todo("NeedsContents")}}
+
+ +

Interfaces

+ +

See DOM Reference

+ +

See also

+ + diff --git a/files/id/web/api/window/window/index.html b/files/id/web/api/window/window/index.html new file mode 100644 index 0000000000..a40d33059f --- /dev/null +++ b/files/id/web/api/window/window/index.html @@ -0,0 +1,63 @@ +--- +title: Window.window +slug: Web/API/Window/window +translation_of: Web/API/Window/window +--- +
{{APIRef}}
+ +

Summary

+ +

Properti window dalam obyek window mengarah pada obyek window itu sendiri. Jadi ekspresi berikut mengembalikan obyek window yang sama:

+ +
window.window
+window.window.window
+window.window.window.window
+  ...
+
+ +

Pada halaman web, obyek window merupakan obyek global. Ini berarti:

+ +
    +
  1. variabel global pada skrip adalah properti dari window: + +
    var global = {data: 0};
    +alert(global === window.global); // displays "true"
    +
    +
  2. +
  3. kamu dapat mengakses properti bawaan dari window tanpa perlu menulis prefix window.: +
    setTimeout("alert('Hi!')", 50); // equivalent to using window.setTimeout.
    +alert(window === window.window); // displays "true"
    +
    +
  4. +
+ +

Tujuan adanya properti window yang mengarah pada obyek itu sendiri adalah mempermudah dalam mengarah pada obyek global. Jika tidak, kamu harus melakukannya secara manual var window = this; dibagian awal skrip.

+ +

Alasan lain, ada beberapa hal yang tidak dapat kamu tulis, contohnya, "{{domxref("window.open","window.open('http://google.com/')")}}". kamu harus menulis "open('http://google.com/')".

+ +

Spesifikasi

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#dom-window', 'Window.window')}}{{Spec2('HTML WHATWG')}}No difference from the latest snapshot {{SpecName("HTML5.1")}}
{{SpecName('HTML5.1', 'browsers.html#dom-window', 'Window.window')}}{{Spec2('HTML5.1')}}No difference from the {{SpecName("HTML5 W3C")}}
{{SpecName('HTML5 W3C', 'browsers.html#dom-window', 'Window.window')}}{{Spec2('HTML5 W3C')}}First snapshot containing the definition of Window.window.
diff --git a/files/id/web/api/xmlhttprequest/index.html b/files/id/web/api/xmlhttprequest/index.html new file mode 100644 index 0000000000..87f02b9550 --- /dev/null +++ b/files/id/web/api/xmlhttprequest/index.html @@ -0,0 +1,200 @@ +--- +title: XMLHttpRequest +slug: Web/API/XMLHttpRequest +tags: + - AJAX + - API + - Communication + - HTTP + - Interface + - NeedsTranslation + - Reference + - TopicStub + - Web + - XHR + - XMLHttpRequest +translation_of: Web/API/XMLHttpRequest +--- +
{{DefaultAPISidebar("XMLHttpRequest")}}
+ +

Use XMLHttpRequest (XHR) objects to interact with servers. You can retrieve data from a URL without having to do a full page refresh. This enables a Web page to update just part of a page without disrupting what the user is doing. XMLHttpRequest is used heavily in {{Glossary("AJAX")}} programming.

+ +

{{InheritanceDiagram(650, 150)}}

+ +

Despite its name, XMLHttpRequest can be used to retrieve any type of data, not just XML.

+ +

If your communication needs to involve receiving event data or message data from a server, consider using server-sent events through the {{domxref("EventSource")}} interface. For full-duplex communication, WebSockets may be a better choice.

+ +

Constructor

+ +
+
{{domxref("XMLHttpRequest.XMLHttpRequest", "XMLHttpRequest()")}}
+
The constructor initializes an XMLHttpRequest. It must be called before any other method calls.
+
+ +

Properties

+ +

This interface also inherits properties of {{domxref("XMLHttpRequestEventTarget")}} and of {{domxref("EventTarget")}}.

+ +
+
{{domxref("XMLHttpRequest.onreadystatechange")}}
+
An {{domxref("EventHandler")}} that is called whenever the readyState attribute changes.
+
{{domxref("XMLHttpRequest.readyState")}} {{readonlyinline}}
+
Returns an unsigned short, the state of the request.
+
{{domxref("XMLHttpRequest.response")}} {{readonlyinline}}
+
Returns an {{jsxref("ArrayBuffer")}}, {{domxref("Blob")}}, {{domxref("Document")}}, JavaScript object, or a {{domxref("DOMString")}}, depending on the value of {{domxref("XMLHttpRequest.responseType")}}, that contains the response entity body.
+
{{domxref("XMLHttpRequest.responseText")}} {{readonlyinline}}
+
Returns a {{domxref("DOMString")}} that contains the response to the request as text, or null if the request was unsuccessful or has not yet been sent.
+
{{domxref("XMLHttpRequest.responseType")}}
+
Is an enumerated value that defines the response type.
+
{{domxref("XMLHttpRequest.responseURL")}} {{readonlyinline}}
+
Returns the serialized URL of the response or the empty string if the URL is null.
+
{{domxref("XMLHttpRequest.responseXML")}} {{readonlyinline}}
+
Returns a {{domxref("Document")}} containing the response to the request, or null if the request was unsuccessful, has not yet been sent, or cannot be parsed as XML or HTML. Not available in workers.
+
{{domxref("XMLHttpRequest.status")}} {{readonlyinline}}
+
Returns an unsigned short with the status of the response of the request.
+
{{domxref("XMLHttpRequest.statusText")}} {{readonlyinline}}
+
Returns a {{domxref("DOMString")}} containing the response string returned by the HTTP server. Unlike {{domxref("XMLHttpRequest.status")}}, this includes the entire text of the response message ("200 OK", for example).
+
+ +
+

Note: According to the HTTP/2 specification (8.1.2.4 Response Pseudo-Header Fields), HTTP/2 does not define a way to carry the version or reason phrase that is included in an HTTP/1.1 status line.

+
+ +
+
{{domxref("XMLHttpRequest.timeout")}}
+
Is an unsigned long representing the number of milliseconds a request can take before automatically being terminated.
+
{{domxref("XMLHttpRequestEventTarget.ontimeout")}}
+
Is an {{domxref("EventHandler")}} that is called whenever the request times out. {{gecko_minversion_inline("12.0")}}
+
{{domxref("XMLHttpRequest.upload")}} {{readonlyinline}}
+
Is an {{domxref("XMLHttpRequestUpload")}}, representing the upload process.
+
{{domxref("XMLHttpRequest.withCredentials")}}
+
Is a {{domxref("Boolean")}} that indicates whether or not cross-site Access-Control requests should be made using credentials such as cookies or authorization headers.
+
+ +

Non-standard properties

+ +
+
{{domxref("XMLHttpRequest.channel")}}{{ReadOnlyInline}}
+
Is a {{Interface("nsIChannel")}}. The channel used by the object when performing the request.
+
{{domxref("XMLHttpRequest.mozAnon")}}{{ReadOnlyInline}}
+
Is a boolean. If true, the request will be sent without cookie and authentication headers.
+
{{domxref("XMLHttpRequest.mozSystem")}}{{ReadOnlyInline}}
+
Is a boolean. If true, the same origin policy will not be enforced on the request.
+
{{domxref("XMLHttpRequest.mozBackgroundRequest")}}
+
Is a boolean. It indicates whether or not the object represents a background service request.
+
{{domxref("XMLHttpRequest.mozResponseArrayBuffer")}}{{gecko_minversion_inline("2.0")}} {{obsolete_inline("6")}} {{ReadOnlyInline}}
+
{{jsxref("ArrayBuffer")}}. The response to the request, as a JavaScript typed array.
+
{{domxref("XMLHttpRequest.multipart")}}{{obsolete_inline("22")}}
+
This Gecko-only feature, a boolean, was removed in Firefox/Gecko 22. Please use Server-Sent Events, Web Sockets, or responseText from progress events instead.
+
+ +

Event handlers

+ +

onreadystatechange as a property of the XMLHttpRequest instance is supported in all browsers.

+ +

Since then, a number of additional event handlers have been implemented in various browsers (onload, onerror, onprogress, etc.). See Using XMLHttpRequest.

+ +

More recent browsers, including Firefox, also support listening to the XMLHttpRequest events via standard {{domxref("EventTarget.addEventListener", "addEventListener()")}} APIs in addition to setting on* properties to a handler function.

+ +

Methods

+ +
+
{{domxref("XMLHttpRequest.abort()")}}
+
Aborts the request if it has already been sent.
+
{{domxref("XMLHttpRequest.getAllResponseHeaders()")}}
+
Returns all the response headers, separated by {{Glossary("CRLF")}}, as a string, or null if no response has been received.
+
{{domxref("XMLHttpRequest.getResponseHeader()")}}
+
Returns the string containing the text of the specified header, or null if either the response has not yet been received or the header doesn't exist in the response.
+
{{domxref("XMLHttpRequest.open()")}}
+
Initializes a request.
+
{{domxref("XMLHttpRequest.overrideMimeType()")}}
+
Overrides the MIME type returned by the server.
+
{{domxref("XMLHttpRequest.send()")}}
+
Sends the request. If the request is asynchronous (which is the default), this method returns as soon as the request is sent.
+
{{domxref("XMLHttpRequest.setRequestHeader()")}}
+
Sets the value of an HTTP request header. You must call setRequestHeader()after open(), but before send().
+
+ +

Non-standard methods

+ +
+
{{domxref("XMLHttpRequest.init()")}}
+
Initializes the object for use from C++ code.
+
+ +
Warning: This method must not be called from JavaScript.
+ +
+
{{domxref("XMLHttpRequest.openRequest()")}}
+
Initializes a request. This method is to be used from native code; to initialize a request from JavaScript code, use open() instead. See the documentation for open().
+
{{domxref("XMLHttpRequest.sendAsBinary()")}}{{deprecated_inline()}}
+
A variant of the send() method that sends binary data.
+
+ +

Events

+ +
+
{{domxref("XMLHttpRequest/abort_event", "abort")}}
+
Fired when a request has been aborted, for example because the program called {{domxref("XMLHttpRequest.abort()")}}.
+ Also available via the {{domxref("XMLHttpRequestEventTarget/onabort", "onabort")}} property.
+
{{domxref("XMLHttpRequest/error_event", "error")}}
+
Fired when the request encountered an error.
+ Also available via the {{domxref("XMLHttpRequestEventTarget/onerror", "onerror")}} property.
+
{{domxref("XMLHttpRequest/load_event", "load")}}
+
Fired when an {{domxref("XMLHttpRequest")}} transaction completes successfully.
+ Also available via the {{domxref("XMLHttpRequestEventTarget/onload", "onload")}} property.
+
{{domxref("XMLHttpRequest/loadend_event", "loadend")}}
+
Fired when a request has completed, whether successfully (after {{domxref("XMLHttpRequest/load_event", "load")}}) or unsuccessfully (after {{domxref("XMLHttpRequest/abort_event", "abort")}} or {{domxref("XMLHttpRequest/error_event", "error")}}).
+ Also available via the {{domxref("XMLHttpRequestEventTarget/onloadend", "onloadend")}} property.
+
{{domxref("XMLHttpRequest/loadstart_event", "loadstart")}}
+
Fired when a request has started to load data.
+ Also available via the {{domxref("XMLHttpRequestEventTarget/onloadstart", "onloadstart")}} property.
+
{{domxref("XMLHttpRequest/progress_event", "progress")}}
+
Fired periodically when a request receives more data.
+ Also available via the {{domxref("XMLHttpRequestEventTarget/onprogress", "onprogress")}} property.
+
{{domxref("XMLHttpRequest/timeout_event", "timeout")}}
+
Fired when progress is terminated due to preset time expiring.
+ Also available via the {{domxref("XMLHttpRequestEventTarget/ontimeout", "ontimeout")}} property.
+
+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('XMLHttpRequest')}}{{Spec2('XMLHttpRequest')}}Live standard, latest version
+ +

Browser compatibility

+ + + +
{{Compat("api.XMLHttpRequest")}}
+ +

See also

+ + diff --git a/files/id/web/api/xmlhttprequest/using_xmlhttprequest/index.html b/files/id/web/api/xmlhttprequest/using_xmlhttprequest/index.html new file mode 100644 index 0000000000..1de088b719 --- /dev/null +++ b/files/id/web/api/xmlhttprequest/using_xmlhttprequest/index.html @@ -0,0 +1,793 @@ +--- +title: Using XMLHttpRequest +slug: Web/API/XMLHttpRequest/Using_XMLHttpRequest +translation_of: Web/API/XMLHttpRequest/Using_XMLHttpRequest +--- +
{{APIRef("XMLHttpRequest")}}
+ +
Dalam panduan ini, kita akan melihat bagaimana cara untuk mengunakan {{domxref("XMLHttpRequest")}}  untuk menyelesaikan permasalahan HTTP request yang dalam penggunaan untuk pertukaran data antara halaman web dan server. Contoh umum dan kasus penggunaan lebih jelas untuk XMLHttpRequest disertakan.
+ +
+ +
Untuk mengirim HTTP request,  buatlah sebuah object XMLHttpRequest , buka sebuah URL dan kirim request tersebut. setelah transaksi selesai, objek akan berisi informasi yang berguna seperti badan respon dan status HTTP dari hasilnya.
+ +
+ +
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();
+ +

Tipe-Tipe dari Request

+ +

Sebuh request yang dihasilkan melalui XMLHttpRequest dapat mengambil data dari salah satu cara, asynchronously or synchronously. Tipe dari request ditentukan onleh opsi async argument (argument ke-tiga) yang telah diset dialam metode {{domxref("XMLHttpRequest.open()")}}. Jika argument tersebut true atau tidak ditentukan. XMLHttpRequest akan diproses secara asynchronous,jika tidak proses akan berjalan secara synchronous. Diskusi detail dan demonstrasi dari kedua cara merequest tersebut dapat ditemukan pada halaman synchronous and asynchronous requests. Jangan gunakan permintaan synchronous di luar Pekerja Web.

+ +
Note: Dimulai dari Gecko 30.0 {{ geckoRelease("30.0") }}, permintaan synchronous pada utas utama telah ditinggalkan karena efek negatif terhadap pengalaman pengguna.
+ +
Note: fungsi konstruksi XMLHttpRequest tidak terbatas hanya pada dokumen XML. Itu dimulai dengan "XML" karena ketika itu dibuat format utama yang awalnya digunakan untuk Asynchronous Data Exchange adalah XML
+ +

Menangani Respons

+ +

Ada beberapa jenis atribut respons  ditentukan oleh spesifikasi standar untuk {domxref("XMLHttpRequest.XMLHttpRequest", "XMLHttpRequest()")}} constructor. Ini memberi tahu klien membuat informasi penting XMLHttpRequest tentang status respons. Beberapa kasus di mana berurusan dengan jenis respons non-teks mungkin melibatkan beberapa manipulasi dan analisis diuraikan dalam bagian berikut.

+ +

Menganalisa dan Memanipulasi Properti responseXML

+ +

Jika kamu mengunakan XMLHttpRequest  untuk mendapatkan konten dokumen XML jarak jauh, properti {{domxref("XMLHttpRequest.responseXML", "responseXML")}}  akan menjadi objek DOM yang berisi dokumen XML parsing. Ini terbentuk sulit untuk dimanipulasi dan dianalisis. Ada empat cara utama untuk menganalisis dokumen XML ini:

+ +
    +
  1. Menggunakan XPath untuk mengatasi (atau menunjuk ke) bagian-bagiannya.
  2. +
  3. Secara manual Parsing dan men-serialisasikan XML ke string atau objek
  4. +
  5. Menggunakan {{domxref("XMLSerializer")}} untuk meng-serialisasi Pohon DOM ke strings atau ke file.
  6. +
  7. {{jsxref("RegExp")}} bisa digunakan jika kamu selalu tau konten dari XML document sebelumnya. Kamu mungkin ingin menghapus jeda baris, jika Anda menggunakan RegEx untuk memindai berkenaan dengan jeda baris. Namun, metode ini adalah "pilihan terakhir" karena jika kode XML sedikit berubah, metode ini kemungkinan akan gagal.
  8. +
+ +
+

Note: XMLHttpRequest sekarang dapat menafsirkan HTML untuk Anda menggunakan properti {{domxref("XMLHttpRequest.responseXML", "responseXML")}}. Baca artikel HTML dalam XMLHttpRequest untuk mempelajari cara untuk melakukannya.

+
+ +

Memproses sebuah Properti responseText yang Berisi HTML Dokument

+ +

Jika kamu mengunakan XMLHttpRequest untuk mendapatkan konten dari halaman web HTML jarak jauh. Properti {{domxref("XMLHttpRequest.responseText", "responseText")}} adalah sebuah string yang berisi data HTML mentah. Hal ini terbukti sulit untuk dimanipulasi dan dianalisi. Karenanya ada tiga cara utama untuk

+ +

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. Ada tiga cara utama untuk menganalisis dan mengurai string HTML mentah ini:

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

+ +

See also

+ +
    +
  1. MDN AJAX introduction
  2. +
  3. HTML in XMLHttpRequest
  4. +
  5. HTTP access control
  6. +
  7. How to check the security state of an XMLHTTPRequest over SSL
  8. +
  9. XMLHttpRequest - REST and the Rich User Experience
  10. +
  11. Microsoft documentation
  12. +
  13. "Using the XMLHttpRequest Object" (jibbering.com)
  14. +
  15. The XMLHttpRequest object: WHATWG specification
  16. +
-- cgit v1.2.3-54-g00ecf