diff options
author | Peter Bengtsson <mail@peterbe.com> | 2020-12-08 14:42:17 -0500 |
---|---|---|
committer | Peter Bengtsson <mail@peterbe.com> | 2020-12-08 14:42:17 -0500 |
commit | da78a9e329e272dedb2400b79a3bdeebff387d47 (patch) | |
tree | e6ef8aa7c43556f55ddfe031a01cf0a8fa271bfe /files/id/web/api | |
parent | 1109132f09d75da9a28b649c7677bb6ce07c40c0 (diff) | |
download | translated-content-da78a9e329e272dedb2400b79a3bdeebff387d47.tar.gz translated-content-da78a9e329e272dedb2400b79a3bdeebff387d47.tar.bz2 translated-content-da78a9e329e272dedb2400b79a3bdeebff387d47.zip |
initial commit
Diffstat (limited to 'files/id/web/api')
34 files changed, 6695 insertions, 0 deletions
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 +--- +<p>{{ APIRef("Web Workers API") }}</p> + +<p>Antarmuka <strong><code>AbstractWorker</code></strong> dari abstrak properti <a href="/en-US/docs/Web/API/Web_Workers_API">Web Workers API</a> dan method umum untuk semua jenis worker, berupa {{domxref("Worker")}} atau {{domxref("SharedWorker")}}.</p> + +<h2 id="Properti">Properti</h2> + +<p><em>Antarmuka <code>AbstractWorker</code></em><em> tidak mewarisi properti apapun.</em></p> + +<h3 id="Event_handlers">Event handlers</h3> + +<dl> + <dt>{{domxref("AbstractWorker.onerror")}}</dt> + <dd>Sebuah {{ domxref("EventListener") }} yang dipanggil ketika sebuah {{domxref("ErrorEvent")}} dari tipe <code>error</code> bubbles melalui worker.</dd> +</dl> + +<h2 id="Method">Method</h2> + +<p><em>Antarmuka <code>AbstractWorker</code></em><em> tidak menjalankan atau mewarisi method apapun.</em></p> + +<h2 id="Contoh">Contoh</h2> + +<p>Catat bahwa anda tidak ingin menggunakan antarmuka <code>AbstractWorker</code> 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:</p> + +<pre class="brush: js">var myWorker = new Worker("worker.js"); + +first.onchange = function() { + myWorker.postMessage([first.value,second.value]); + console.log('Message posted to worker'); +}</pre> + +<p>Contoh lengkapnya, lihat:</p> + +<ul> + <li><a class="external external-icon" href="https://github.com/mdn/simple-web-worker">Basic dedicated worker example</a> (<a class="external external-icon" href="http://mdn.github.io/simple-web-worker/">run dedicated worker</a>).</li> + <li><a class="external external-icon" href="https://github.com/mdn/simple-shared-worker">Basic shared worker example</a> (<a class="external external-icon" href="http://mdn.github.io/simple-shared-worker/">run shared worker</a>).</li> +</ul> + +<h2 id="Spesifikasi">Spesifikasi</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Spesifikasi</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName("HTML WHATWG", "#the-abstractworker-abstract-interface", "AbstractWorker")}}</td> + <td>{{Spec2("HTML WHATWG")}}</td> + <td>No change from {{SpecName("Web Workers")}}.</td> + </tr> + <tr> + <td>{{SpecName("Web Workers", "#the-abstractworker-abstract-interface", "AbstractWorker")}}</td> + <td>{{Spec2("Web Workers")}}</td> + <td>Initial definition.</td> + </tr> + </tbody> +</table> + +<h2 id="Kompabilitas_Browser">Kompabilitas Browser</h2> + +<div>{{CompatibilityTable()}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Fitur</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari (WebKit)</th> + </tr> + <tr> + <td>Dukungan dasar</td> + <td>{{CompatChrome(4)}}</td> + <td>{{CompatGeckoDesktop("1.9.1")}}</td> + <td>10</td> + <td>10.6</td> + <td>4</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Fitur</th> + <th>Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>Firefox OS (Gecko)</th> + <th>IE Phone</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Dukungan dasar</td> + <td>4.4</td> + <td>{{CompatGeckoMobile("1.9.1")}}</td> + <td>1.0.1</td> + <td>10</td> + <td>11.5</td> + <td>5.1</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Lihat_Juga">Lihat Juga</h2> + +<ul> + <li>{{domxref("Worker")}} dan {{domxref("SharedWorker")}} mewarisinya.</li> +</ul> + +<p> </p> 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 +--- +<div>{{DefaultAPISidebar("Push API")}}{{SeeCompatTable}}</div> + +<p><strong>API Push</strong> 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.</p> + +<div class="note"> +<p><strong>Catatan</strong>: Dokumentasi ini melingkupi spesifikasi API Push W3C. Bila Anda mencari dokumentasi untuk mekanisme berpemilik dari Firefox OS, lihat <a href="/id/docs/Web/API/Simple_Push_API">Push Sederhana</a>.</p> +</div> + +<h2 id="Push_concepts_and_usage">Push concepts and usage</h2> + +<p>For an app to receive push messages, it has to have an active <a href="/en-US/docs/Web/API/ServiceWorker_API">service worker</a>. When the service worker is active, it can subscribe to push notifications using {{domxref("PushManager.subscribe()")}}.</p> + +<p>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.</p> + +<p>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()")}}.)</p> + +<p>Each subscription is unique to a service worker. The endpoint for the subscription is a unique <a href="http://www.w3.org/TR/capability-urls/">capability URL</a>: 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.</p> + +<p>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.</p> + +<div class="note"> +<p><strong>Note</strong>: 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.</p> +</div> + +<div class="note"> +<p><strong>Note</strong>: Chrome currently requires you to set up a project on <a href="https://developers.google.com/cloud-messaging/">Google Cloud Messaging</a> 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.</p> +</div> + +<h2 id="Interfaces">Interfaces</h2> + +<dl> + <dt>{{domxref("PushEvent")}}</dt> + <dd>Represents a push action sent to the <a href="/en-US/docs/Web/API/ServiceWorkerGlobalScope">global scope</a> of a {{domxref("ServiceWorker")}}. It contains information sent from an application to a {{domxref("PushSubscription")}}.</dd> + <dt>{{domxref("PushManager")}}</dt> + <dd>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.</dd> + <dt>{{domxref("PushMessageData")}}</dt> + <dd>Provides access to push data sent by a server, and includes methods to manipulate the received data.</dd> + <dt>{{domxref("PushSubscription")}}</dt> + <dd>Provides a subcription's URL endpoint and allows unsubscription from a push service.</dd> +</dl> + +<h2 id="Service_worker_additions">Service worker additions</h2> + +<p>The following additions to the <a href="/en-US/docs/Web/API/Service_Worker_API">Service Worker API</a> 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.</p> + +<dl> + <dt>{{domxref("ServiceWorkerRegistration.pushManager")}} {{readonlyinline}}</dt> + <dd>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.</dd> + <dt>{{domxref("ServiceWorkerGlobalScope.onpush")}}</dt> + <dd>An event handler fired whenever a {{Event("push")}} event occurs; that is, whenever a server push message is received.</dd> + <dt>{{domxref("ServiceWorkerGlobalScope.onpushsubscriptionchange")}}</dt> + <dd>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.)</dd> +</dl> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName("Push API")}}</td> + <td>{{Spec2("Push API")}}</td> + <td>Initial definition</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_Compatibility">Browser Compatibility</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari (WebKit)</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatChrome(42.0)}}</td> + <td>{{CompatGeckoDesktop(44.0)}}<sup>[1]</sup></td> + <td>{{CompatNo}}<sup>[2]</sup></td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td>{{domxref("PushEvent.data")}},<br> + {{domxref("PushMessageData")}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatGeckoDesktop(44.0)}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Android Webview</th> + <th>Firefox Mobile (Gecko)</th> + <th>Firefox OS</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + <th>Chrome for Android</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}<sup>[2]</sup></td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatChrome(42.0)}}</td> + </tr> + <tr> + <td>{{domxref("PushEvent.data")}},<br> + {{domxref("PushMessageData")}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + </tbody> +</table> +</div> + +<p>[1] Currently available only on desktop versions of Firefox; also, push messages are only delivered when Firefox is running.</p> + +<p>[2] This is currently not implemented. See the <a href="https://dev.modern.ie/platform/status/pushapi/">Microsoft Edge status information</a>.</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="/en-US/docs/Web/API/Push_API/Using_the_Push_API">Using the Push API</a></li> + <li><a href="https://github.com/chrisdavidmills/push-api-demo">Push API Demo</a>, on Github</li> + <li><a href="http://updates.html5rocks.com/2015/03/push-notificatons-on-the-open-web">Push Notifications on the Open Web</a>, Matt Gaunt</li> + <li><a href="/en-US/docs/Web/API/Service_Worker_API">Service Worker API</a></li> +</ul> 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 +--- +<p>{{APIRef("Service Workers API")}}</p> + +<p>The <strong><code>CacheStorage</code></strong> interface represents the storage for {{domxref("Cache")}} objects.</p> + +<p>The interface:</p> + +<ul> + <li>Provides a master directory of all the named caches that can be accessed by a {{domxref("ServiceWorker")}} or other type of worker or {{domxref("window")}} scope (you’re not limited to only using it with service workers, even though the {{SpecName('Service Workers')}} spec defines it). + <div class="note"><strong>Note</strong>: <a href="https://bugs.chromium.org/p/chromium/issues/detail?id=1026063">Chrome and Safari only expose `CacheStorage` to the windowed context over HTTPS</a>. {{domxref("window.caches")}} will be undefined unless an SSL certificate is configured.</div> + </li> + <li>Maintains a mapping of string names to corresponding {{domxref("Cache")}} objects.</li> +</ul> + +<p>Use {{domxref("CacheStorage.open()")}} to obtain a {{domxref("Cache")}} instance.</p> + +<p>Use {{domxref("CacheStorage.match()")}} to check if a given {{domxref("Request")}} is a key in any of the {{domxref("Cache")}} objects that the <code>CacheStorage</code> object tracks.</p> + +<p>You can access <code>CacheStorage</code> through the global {{domxref("WindowOrWorkerGlobalScope.caches", "caches")}} property.</p> + +<div class="note"><strong>Note</strong>: CacheStorage always rejects with a <code>SecurityError</code> 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.</div> + +<div class="note"><strong>Note</strong>: {{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()")}}.</div> + +<h2 id="Methods">Methods</h2> + +<dl> + <dt>{{domxref("CacheStorage.match()")}}</dt> + <dd>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.</dd> + <dt>{{domxref("CacheStorage.has()")}}</dt> + <dd>Returns a {{jsxref("Promise")}} that resolves to <code>true</code> if a {{domxref("Cache")}} object matching the <code>cacheName</code> exists.</dd> + <dt>{{domxref("CacheStorage.open()")}}</dt> + <dd>Returns a {{jsxref("Promise")}} that resolves to the {{domxref("Cache")}} object matching the <code>cacheName</code> (a new cache is created if it doesn't already exist.)</dd> + <dt>{{domxref("CacheStorage.delete()")}}</dt> + <dd>Finds the {{domxref("Cache")}} object matching the <code>cacheName</code>, and if found, deletes the {{domxref("Cache")}} object and returns a {{jsxref("Promise")}} that resolves to <code>true</code>. If no {{domxref("Cache")}} object is found, it resolves to <code>false</code>.</dd> + <dt>{{domxref("CacheStorage.keys()")}}</dt> + <dd>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.</dd> +</dl> + +<h2 id="Examples">Examples</h2> + +<p>This code snippet is from the MDN <a href="https://github.com/mdn/sw-test/">sw-test example</a> (see <a href="https://mdn.github.io/sw-test/">sw-test running live</a>.) 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.</p> + +<p>In the second code block, we wait for a {{domxref("FetchEvent")}} to fire. We construct a custom response like so:</p> + +<ol> + <li>Check whether a match for the request is found in the CacheStorage. If so, serve that.</li> + <li>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")}} (<code>cache.put(event.request, response.clone())</code>.)</li> + <li>If this fails (e.g. because the network is down), return a fallback response.</li> +</ol> + +<p>Finally, return whatever the custom response ended up being equal to, using {{domxref("FetchEvent.respondWith")}}.</p> + +<pre class="brush: js notranslate">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'); + }); + } + })); +}); +</pre> + +<p>This snippet shows how the API can be used outside of a service worker context, and uses the <code>await</code> operator for much more readable code.</p> + +<pre class="brush: js notranslate">// 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 } ); +}</pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('Service Workers', '#cachestorage', 'CacheStorage')}}</td> + <td>{{Spec2('Service Workers')}}</td> + <td>Initial definition.</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + + + +<p>{{Compat("api.CacheStorage")}}</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker_API/Using_Service_Workers">Using Service Workers</a></li> + <li>{{domxref("Cache")}}</li> + <li>{{domxref("WindowOrWorkerGlobalScope.caches")}}</li> +</ul> 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 +--- +<div>{{CanvasSidebar}}</div> + +<p class="summary">Ditambahkan di <a href="/en-US/docs/HTML/HTML5">HTML5</a>, <strong>elemen HTML {{HTMLElement("canvas")}} </strong>dapat digunakan untuk menggambar grafik melalui skrip di <a href="/en-US/docs/Web/JavaScript">JavaScript</a>. Sebagai contoh, dapat digunakan untuk menggambar graf, membuat komposisi foto, mencipta animasi, atau bahkan melakukan pemrosesan atau rendering video secara waktu-nyata .</p> + +<p>Aplikasi Mozilla mendapat dukungan untuk <code><canvas></code> sejak Gecko 1.8 (i.e. <a href="/en-US/docs/Mozilla/Firefox/Releases/1.5">Firefox 1.5</a>). Elemen tersebut semula dikenalkan oleh Apple untuk Dashboard OS X dan Safari. Internet Explorer mendukung <code><canvas></code> sejak versi 9 dan seterusnya; untuk versi awal IE, sebuah halaman dapat secara efektif mendukung <code><canvas></code> dengan memasukkan skrip dari proyek <a href="https://github.com/arv/explorercanvas">Explorer Canvas</a> Google. Google Chrome dan Opera 9 juga mendukung <code><canvas></code>.</p> + +<p>Elemen <code><canvas></code> juga digunakan oleh <a href="/en-US/docs/Web/WebGL">WebGL</a> untuk menggambar grafik hardware-accelerated 3D di halaman web.</p> + +<h2 id="Contoh">Contoh</h2> + +<p>Ini hanya cuplikan kode sederhana yang menggunakan metode {{domxref("CanvasRenderingContext2D.fillRect()")}}.</p> + +<h3 id="HTML">HTML</h3> + +<pre class="brush: html"><canvas id="canvas"></canvas> +</pre> + +<h3 id="JavaScript">JavaScript</h3> + +<pre class="brush: js">var canvas = document.getElementById('canvas'); +var ctx = canvas.getContext('2d'); + +ctx.fillStyle = 'green'; +ctx.fillRect(10, 10, 100, 100); +</pre> + +<p>Edit kode di bawah dan lihat perbaruan perubahannya di kanvas secara waktu-nyata:</p> + +<div class="hidden"> +<h6 id="Playable_code">Playable code</h6> + +<pre class="brush: html"><canvas id="canvas" width="400" height="200" class="playable-canvas"></canvas> +<div class="playable-buttons"> + <input id="edit" type="button" value="Edit" /> + <input id="reset" type="button" value="Reset" /> +</div> +<textarea id="code" class="playable-code"> +ctx.fillStyle = 'green'; +ctx.fillRect(10, 10, 100, 100);</textarea> +</pre> + +<pre class="brush: js">var canvas = document.getElementById('canvas'); +var ctx = canvas.getContext("2d"); +var textarea = document.getElementById('code'); +var reset = document.getElementById('reset'); +var edit = document.getElementById('edit'); +var code = textarea.value; + +function drawCanvas() { + ctx.clearRect(0, 0, canvas.width, canvas.height); + eval(textarea.value); +} + +reset.addEventListener('click', function() { + textarea.value = code; + drawCanvas(); +}); + +edit.addEventListener('click', function() { + textarea.focus(); +}) + +textarea.addEventListener('input', drawCanvas); +window.addEventListener('load', drawCanvas); +</pre> +</div> + +<p>{{ EmbedLiveSample('Playable_code', 700, 360) }}</p> + +<h2 id="Reference">Reference</h2> + +<div class="index"> +<ul> + <li>{{domxref("HTMLCanvasElement")}}</li> + <li>{{domxref("CanvasRenderingContext2D")}}</li> + <li>{{domxref("CanvasGradient")}}</li> + <li>{{domxref("CanvasImageSource")}}</li> + <li>{{domxref("CanvasPattern")}}</li> + <li>{{domxref("ImageBitmap")}}</li> + <li>{{domxref("ImageData")}}</li> + <li>{{domxref("RenderingContext")}}</li> + <li>{{domxref("TextMetrics")}}</li> + <li>{{domxref("OffscreenCanvas")}}{{experimental_inline}}</li> + <li>{{domxref("Path2D")}} {{experimental_inline}}{{domxref("ImageBitmapRenderingContext")}}{{experimental_inline}}</li> +</ul> +</div> + +<p>The interfaces related to the <code>WebGLRenderingContext</code> are referenced under <a href="/en-US/docs/Web/WebGL" title="/en-US/docs/Web/WebGL">WebGL</a>.</p> + +<p>{{domxref("CanvasCaptureMediaStream")}} is related.</p> + +<h2 id="Petunjuk_dan_tutorial">Petunjuk dan tutorial</h2> + +<dl> + <dt><a href="/en-US/docs/Web/API/Canvas_API/Tutorial">Tutorial canvas</a></dt> + <dd>Tutorial komprehensif mengcakup penggunaan sederhana <code><canvas></code> dan fitur lanjutannya.</dd> + <dt><a href="/en-US/Add-ons/Code_snippets/Canvas">Cuplikan kode: Canvas</a></dt> + <dd><span id="result_box" lang="id"><span>Beberapa cuplikan kode pengembang berorientasi ekstensi yang melibatkan</span></span> <code><canvas></code>.</dd> + <dt><a href="/en-US/docs/Web/API/Canvas_API/A_basic_ray-caster">Demo: ray-caster sederhana</a></dt> + <dd>Demo animasi ray-tracing menggunakan canvas.</dd> + <dt><a href="/en-US/docs/Web/API/Canvas_API/Drawing_DOM_objects_into_a_canvas">Menggambar DOM objects ke canvas</a></dt> + <dd>Bagaimana menggambar konten DOM, seperti elemen HTML, pada canvas.</dd> + <dt><a href="/en-US/docs/Web/API/Canvas_API/Manipulating_video_using_canvas">Memanipulasi video dengan canvas</a></dt> + <dd>Menggabungkan {{HTMLElement("video")}} dan {{HTMLElement("canvas")}} untuk memanipulasi data video secara real time.</dd> +</dl> + +<h2 id="Sumber">Sumber</h2> + +<h3 id="Generik">Generik</h3> + +<ul> + <li><a href="http://joshondesign.com/p/books/canvasdeepdive/title.html">HTML5 Canvas Deep Dive</a></li> + <li><a href="http://bucephalus.org/text/CanvasHandbook/CanvasHandbook.html">Canvas Handbook</a></li> +</ul> + +<h3 id="Librari">Librari</h3> + +<ul> + <li><a href="http://fabricjs.com">Fabric.js</a> is an open-source canvas library with SVG parsing capabilities.</li> + <li><a href="https://github.com/ericdrowell/KineticJS">Kinetic.js</a> is an open-source canvas library focused on interactivity for desktop and mobile applications.</li> + <li><a href="http://paperjs.org/">Paper.js</a> is an open source vector graphics scripting framework that runs on top of the HTML5 Canvas.</li> + <li><a href="http://origamijs.com/docs/">Origami.js</a> is an open source lightweight canvas library.</li> + <li><a href="http://libcanvas.github.com/">libCanvas</a> is powerful and lightweight canvas framework.</li> + <li><a href="https://p5js.org/">p5.js </a>has a full set of canvas drawing functionality for artists, designers, educators and beginners.</li> + <li><a href="http://processingjs.org">Processing.js</a> is a port of the Processing visualization language.</li> + <li><a href="https://playcanvas.com/">PlayCanvas</a> is an open source game engine.</li> + <li><a href="http://www.pixijs.com/">Pixi.js</a> adalah enjine permainan open source.</li> + <li><a href="http://www.liquidx.net/plotkit/">PlotKit</a> adalah librari charting dan grafik.</li> + <li><a class="link-https" href="https://github.com/jeremyckahn/rekapi">Rekapi</a> is an animation key-framing API for Canvas.</li> + <li><a href="http://senchalabs.github.com/philogl/">PhiloGL</a> is a WebGL framework for data visualization, creative coding and game development.</li> + <li><a href="http://thejit.org/">JavaScript InfoVis Toolkit</a> creates interactive 2D Canvas data visualizations for the Web.</li> + <li><a href="http://www.createjs.com/easeljs">EaselJS</a> is a free/open source library to make it easier to use canvas for games and art</li> + <li><a href="http://scrawl.rikweb.org.uk/">Scrawl-canvas</a> is another open-source javascript library for creating and manipulating 2d canvas elements</li> + <li><a href="https://www.patrick-wied.at/static/heatmapjs/">heatmap.js</a> is an open source library to create canvas based heatmaps</li> + <li>The <a href="http://zimjs.com">ZIM</a> framework provides conveniences, components and controls for coding creativity on the canvas — includes accessibility and hundreds of colorful tutorials.</li> +</ul> + +<h2 id="Spesifikasi">Spesifikasi</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Spesifikasi</th> + <th scope="col">Status</th> + <th scope="col">Komentar</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('HTML WHATWG', 'scripting.html#the-canvas-element', '<canvas>')}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="Lihat_juga">Lihat juga</h2> + +<ul> + <li><a href="/en-US/docs/Web/WebGL">WebGL</a></li> +</ul> 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 +--- +<div>{{APIRef("Console API")}}</div> + +<p>The <strong><code>Console</code></strong> object provides access to the browser's debugging console (e.g., the <a href="/en-US/docs/Tools/Web_Console">Web Console</a> in Firefox). The specifics of how it works vary from browser to browser, but there is a <em>de facto</em> set of features that are typically provided.</p> + +<p>The <code>Console</code> 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 <code>console</code>. For example:</p> + +<pre class="brush: js">console.log("Failed to open the specified link")</pre> + +<p>This page documents the {{anch("Methods")}} available on the <code>Console</code> object and gives a few {{anch("Usage")}} examples.</p> + +<p>{{AvailableInWorkers}}</p> + +<h2 id="Methods">Methods</h2> + +<dl> + <dt>{{domxref("Console.assert()")}}</dt> + <dd>Log a message and stack trace to console if first argument is <code>false</code>.</dd> + <dt>{{domxref("Console.clear()")}}</dt> + <dd>Clear the console.</dd> + <dt>{{domxref("Console.count()")}}</dt> + <dd>Log the number of times this line has been called with the given label.</dd> + <dt>{{domxref("Console.debug()")}}</dt> + <dd>An alias for <code>log() - starting with Chromium 58 this method is a no-op on Chromium browsers.</code></dd> + <dt>{{domxref("Console.dir()")}} {{Non-standard_inline}}</dt> + <dd>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.</dd> + <dt>{{domxref("Console.dirxml()")}} {{Non-standard_inline}}</dt> + <dd> + <p>Displays an XML/HTML Element representation of the specified object if possible or the JavaScript Object view if it is not.</p> + </dd> + <dt>{{domxref("Console.error()")}}</dt> + <dd>Outputs an error message. You may use <a href="/en-US/docs/Web/API/console#Using_string_substitutions">string substitution</a> and additional arguments with this method.</dd> + <dt>{{domxref("Console.exception()")}} {{Non-standard_inline}} {{deprecated_inline}}</dt> + <dd>An alias for <code>error()</code></dd> + <dt>{{domxref("Console.group()")}}</dt> + <dd>Creates a new inline <a href="/en-US/docs/Web/API/console#Using_groups_in_the_console">group</a>, indenting all following output by another level. To move back out a level, call <code>groupEnd()</code>.</dd> + <dt>{{domxref("Console.groupCollapsed()")}}</dt> + <dd>Creates a new inline <a href="/en-US/docs/Web/API/console#Using_groups_in_the_console">group</a>, indenting all following output by another level; unlike <code>group()</code>, this starts with the inline group collapsed, requiring the use of a disclosure button to expand it. To move back out a level, call <code>groupEnd()</code>.</dd> + <dt>{{domxref("Console.groupEnd()")}}</dt> + <dd>Exits the current inline <a href="/en-US/docs/Web/API/console#Using_groups_in_the_console">group</a>.</dd> + <dt>{{domxref("Console.info()")}}</dt> + <dd>Informative logging information. You may use <a href="/en-US/docs/Web/API/console#Using_string_substitutions">string substitution</a> and additional arguments with this method.</dd> + <dt>{{domxref("Console.log()")}}</dt> + <dd>For general output of logging information. You may use <a href="/en-US/docs/Web/API/console#Using_string_substitutions">string substitution</a> and additional arguments with this method.</dd> + <dt>{{domxref("Console.profile()")}} {{Non-standard_inline}}</dt> + <dd>Starts the browser's build-in profiler (for example, the <a href="/en-US/docs/Tools/Performance">Firefox performance tool</a>). You can specify an optional name for the profile.</dd> + <dt>{{domxref("Console.profileEnd()")}} {{Non-standard_inline}}</dt> + <dd>Stops the profiler. You can see the resulting profile in the browser's performance tool (for example, the <a href="/en-US/docs/Tools/Performance">Firefox performance tool</a>).</dd> + <dt>{{domxref("Console.table()")}}</dt> + <dd>Displays tabular data as a table.</dd> + <dt>{{domxref("Console.time()")}}</dt> + <dd>Starts a <a href="/en-US/docs/Web/API/console#Timers">timer</a> with a name specified as an input parameter. Up to 10,000 simultaneous timers can run on a given page.</dd> + <dt>{{domxref("Console.timeEnd()")}}</dt> + <dd>Stops the specified <a href="/en-US/docs/Web/API/console#Timers">timer</a> and logs the elapsed time in seconds since its start.</dd> + <dt>{{domxref("Console.timeStamp()")}} {{Non-standard_inline}}</dt> + <dd>Adds a marker to the browser's <a href="https://developer.chrome.com/devtools/docs/timeline">Timeline</a> or <a href="/en-US/docs/Tools/Performance/Waterfall">Waterfall</a> tool.</dd> + <dt>{{domxref("Console.trace()")}}</dt> + <dd>Outputs a <a href="/en-US/docs/Web/API/console#Stack_traces">stack trace</a>.</dd> + <dt>{{domxref("Console.warn()")}}</dt> + <dd>Outputs a warning message. You may use <a href="/en-US/docs/Web/API/console#Using_string_substitutions">string substitution</a> and additional arguments with this method.</dd> +</dl> + + +<h2 id="Usage" name="Usage">Usage</h2> + +<h3 id="Outputting_text_to_the_console" name="Outputting_text_to_the_console">Outputting text to the console</h3> + +<p>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.</p> + +<p>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.</p> + +<h4 id="Outputting_a_single_object">Outputting a single object</h4> + +<p>The simplest way to use the logging methods is to output a single object:</p> + +<pre class="brush: js">var someObject = { str: "Some text", id: 5 }; +console.log(someObject); +</pre> + +<p>The output looks something like this:</p> + +<pre>[09:27:13.475] ({str:"Some text", id:5})</pre> + +<h4 id="Outputting_multiple_objects">Outputting multiple objects</h4> + +<p>You can also output multiple objects by simply listing them when calling the logging method, like this:</p> + +<pre class="brush: js">var car = "Dodge Charger"; +var someObject = {str:"Some text", id:5}; +console.info("My first car was a", car, ". The object is: ", someObject);</pre> + +<p>This output will look like this:</p> + +<pre>[09:28:22.711] My first car was a Dodge Charger . The object is: ({str:"Some text", id:5}) +</pre> + +<h4 id="Using_string_substitutions">Using string substitutions</h4> + +<p>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:</p> + +<table class="standard-table" style="width: auto;"> + <tbody> + <tr> + <td class="header">Substitution string</td> + <td class="header">Description</td> + </tr> + <tr> + <td>%o or %O</td> + <td>Outputs a JavaScript object. Clicking the object name opens more information about it in the inspector.</td> + </tr> + <tr> + <td>%d or %i</td> + <td>Outputs an integer. Number formatting is supported, for example <code>console.log("Foo %.2d", 1.1)</code> will output the number as two significant figures with a leading 0: <code>Foo 01</code></td> + </tr> + <tr> + <td>%s</td> + <td>Outputs a string.</td> + </tr> + <tr> + <td>%f</td> + <td>Outputs a floating-point value. Formatting is supported, for example <code>console.log("Foo %.2f", 1.1)</code> will output the number to 2 decimal places: <code>Foo 1.10</code></td> + </tr> + </tbody> +</table> + +<p>Each of these pulls the next argument after the format string off the parameter list. For example:</p> + +<pre>for (var i=0; i<5; i++) { + console.log("Hello, %s. You've called me %d times.", "Bob", i+1); +} +</pre> + +<p>The output looks like this:</p> + +<pre>[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. +</pre> + +<h4 id="Styling_console_output">Styling console output</h4> + +<p>You can use the <code>"%c"</code> directive to apply a CSS style to console output:</p> + +<pre class="brush: js">console.log("This is %cMy stylish message", "color: yellow; font-style: italic; background-color: blue;padding: 2px");</pre> + +<div>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.</div> + +<div> </div> + +<div><img alt="" src="https://mdn.mozillademos.org/files/12527/CSS-styling.png" style="display: block; margin: 0 auto;"></div> + +<div> </div> + +<div class="note"> +<p><strong>Note</strong>: Quite a few CSS properties are supported by this styling; you should experiment and see which ones prove useful.</p> +</div> + +<div> </div> + +<div>{{h3_gecko_minversion("Using groups in the console", "9.0")}}</div> + +<p>You can use nested groups to help organize your output by visually combining related material. To create a new nested block, call <code>console.group()</code>. The <code>console.groupCollapsed()</code> method is similar, but creates the new block collapsed, requiring the use of a disclosure button to open it for reading.</p> + +<div class="note"><strong>Note:</strong> Collapsed groups are not supported yet in Gecko; the <code>groupCollapsed()</code> method is the same as <code>group()</code> at this time.</div> + +<p>To exit the current group, simply call console.groupEnd(). For example, given this code:</p> + +<pre class="brush: js">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"); +</pre> + +<p>The output looks like this:</p> + +<p><img alt="nesting.png" class="default internal" src="/@api/deki/files/6082/=nesting.png"></p> + +<div>{{h3_gecko_minversion("Timers", "10.0")}}</div> + +<p>In order to calculate the duration of a specific operation, Gecko 10 introduced the support of timers in the <code>console</code> object. To start a timer, call the <code>console.time</code><code>()</code> method, giving it a name as the only parameter. To stop the timer, and to get the elapsed time in milliseconds, just call the <code>console.timeEnd()</code> method, again passing the timer's name as the parameter. Up to 10,000 timers can run simultaneously on a given page.</p> + +<p>For example, given this code:</p> + +<pre class="brush: js">console.time("answer time"); +alert("Click to continue"); +console.timeEnd("answer time"); +</pre> + +<p>will log the time needed by the user to discard the alert box:</p> + +<p><img alt="timerresult.png" class="default internal" src="/@api/deki/files/6084/=timerresult.png"></p> + +<p>Notice that the timer's name is displayed both when the timer is started and when it's stopped.</p> + +<div class="note"><strong>Note:</strong> 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.</div> + +<h3 id="Stack_traces">Stack traces</h3> + +<p>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:</p> + +<pre class="brush: js">function foo() { + function bar() { + console.trace(); + } + bar(); +} + +foo(); +</pre> + +<p>The output in the console looks something like this:</p> + +<p><img alt="" src="https://mdn.mozillademos.org/files/7167/api-trace2.png" style="display: block; margin-left: auto; margin-right: auto;"></p> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('Console API')}}</td> + <td>{{Spec2('Console API')}}</td> + <td>Initial definition.</td> + </tr> + </tbody> +</table> + +<h2 id="Notes">Notes</h2> + +<ul> + <li>At least in Firefox, if a page defines a <code>console</code> object, that object overrides the one built into Firefox.</li> + <li>Prior to {{Gecko("12.0")}}, the console object's methods only work when the Web Console is open. Starting with {{Gecko("12.0")}}, output is cached until the Web Console is opened, then displayed at that time.</li> + <li>It's worth noting that the Firefox's built-in <code>Console</code> object is compatible with the one provided by <a class="external" href="http://getfirebug.com/" title="http://getfirebug.com/">Firebug</a>.</li> +</ul> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="/en-US/docs/Tools" title="Tools">Tools</a></li> + <li><a href="/en-US/docs/Tools/Web_Console" title="Web Console">Web Console</a> — how the Web Console in Firefox handles console API calls</li> + <li><a href="/en-US/docs/Tools/Remote_Debugging">Remote debugging</a> — how to see console output when the debugging target is a mobile device</li> + <li><a href="/en-US/docs/Mozilla/Firefox_OS/Debugging/On-device_console_logging" title="/en-US/docs/Mozilla/Firefox_OS/Debugging/On-device_console_logging">On-device console logging</a> — how to do logging on Firefox OS devices</li> +</ul> + +<h3 id="Other_implementations">Other implementations</h3> + +<ul> + <li><a href="https://developers.google.com/chrome-developer-tools/docs/console-api">Google Chrome DevTools</a></li> + <li><a href="http://getfirebug.com/wiki/index.php/Console_API">Firebug</a></li> + <li><a href="http://msdn.microsoft.com/en-us/library/hh772173(v=vs.85).aspx">Internet Explorer</a></li> + <li><a href="https://developer.apple.com/library/safari/documentation/AppleApplications/Conceptual/Safari_Developer_Guide/Console/Console.html">Safari</a></li> +</ul> 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 +--- +<div>{{APIRef("DOM")}}</div> + +<p>Dalam sebuah dokumen <a href="/en-US/docs/Web/HTML">HTML</a>, metode <strong><code>document.createElement()</code></strong> membuat elemen HTML yang ditentukan oleh <code>tagName</code>, atau sebuah {{domxref("HTMLUnknownElement")}} jika <code>tagName</code> tidak dikenali.</p> + +<div class="note"> +<p><strong>Catatan</strong>: Dalam sebuah dokumen <a href="/en-US/docs/Mozilla/Tech/XUL">XUL</a> , ini membuat elemen XUL yang ditentukan. Pada dokumen lain, ini membuat sebuah elemen dengan sebuah namespace URI yang <code>null</code>.</p> +</div> + +<h2 id="Sintaks">Sintaks</h2> + +<pre class="brush: js"><var>var <em>element</em></var> = <var>document</var>.createElement(<em><var>tagName[, options]</var></em>); +</pre> + +<h3 id="Parameter">Parameter</h3> + +<dl> + <dt><code>tagName</code></dt> + <dd>Sebuah <em>string</em> yang menentukan tipe dari elemen yang akan dibuat. {{domxref("Node.nodeName", "nodeName")}} dari elemen dibuat dengan nilai <code>tagName</code>. Jangan menggunakan nama yang memenuhi syarat (seperti "html:a") dengan metode ini. Ketika dipanggil pada sebuah dokumen HTML, <code>createElement()</code> mengubah <code>tagName</code> menjadi <em>lower case</em> sebelum membuat elemen. Pada Firefox, Opera, dan Chrome, <code>createElement(null)</code> bekerja seperti <code>createElement("null")</code>.</dd> + <dt><code>options</code>{{optional_inline}}</dt> + <dd>Sebuah objek opsional <code>ElementCreationOptions</code> berisi sebuah properti tunggal bernama <code>is</code>, yang nilainya adalah nama tag untuk sebuah elemen khusus yang sebelumnya didefinisikan menggunakan <code>customElements.define()</code>. Lihat {{anch("Web component example")}} untuk lebih jelasnya.</dd> +</dl> + +<h3 id="Return_value"><em>Return value</em></h3> + +<p><a href="https://developer.mozilla.org/en-US/docs/Web/API/Element" title="The Element interface represents an object of a Document. This interface describes methods and properties common to all kinds of elements. Specific behaviors are described in interfaces which inherit from Element but add additional functionality."><code>Element</code></a> baru.</p> + +<h2 id="Contoh">Contoh</h2> + +<h3 id="Contoh_dasar">Contoh dasar</h3> + +<p>Ini membuat sebuah <code><div></code> baru dan memasukannya sebelum elemen dengan ID "<code>div1</code>".</p> + +<h4 id="HTML">HTML</h4> + +<pre class="brush: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> +</pre> + +<h4 id="JavaScript"><span style="line-height: normal;">JavaScript</span></h4> + +<pre class="brush:js">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); +}</pre> + +<p>{{EmbedLiveSample("Basic_example", 500, 50)}}</p> + +<h3 id="Contoh_komponen_web">Contoh komponen web</h3> + +<p>Contoh cuplikan berikut diambil dari contoh dari <em>expanding-list-web-component</em> kami (lihat juga secara langsung). Dalam kasus ini, elemen khusus kami memperluas {{domxref("HTMLUListElement")}}, yang mewakili elemen {{htmlelement("ul")}}.</p> + +<pre>// Membuat sebuah kelas untuk elemen +class ExpandingList extends HTMLUListElement { + constructor() { + // Selalu memanggil <em>super</em> dulu di konstruktor + super(); + + // definisi konstruktor dihilangkan untuk singkatnya + ... + } +} + +// Mendefinisi elemen baru +customElements.define('expanding-list', ExpandingList, { extends: "ul" });</pre> + +<p>Jika kita ingin untuk membuat sebuah <em>instance</em> dari elemen ini secara terprogram, kita akan menggunakan sebuah panggilan di sepanjang baris berikut:</p> + +<pre class="brush: js">let expandingList = document.createElement('ul', { is : 'expanding-list' })</pre> + +<p>Elemen baru akan diberikan sebuah atribut <code><a href="/en-US/docs/Web/HTML/Global_attributes/is">is</a></code> yang nilainya adalah nama tag elemen khusus.</p> + +<div class="note"> +<p><strong>Catatan</strong>: Untuk kompabilitas ke belakang untuk versi sebelumnya dari <a href="https://www.w3.org/TR/custom-elements/">Spesifikasi Elemen khusus</a>, beberapa peramban (<em>browser</em>) akan memungkinkan Anda untuk melewatkan sebuah <em>string</em> di sini bukan pada sebuah objek, yang mana nilai <em>string </em> adalah nama tag elemen khusus.</p> +</div> + +<h2 id="Spesifikasi">Spesifikasi</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Spesifikasi</th> + <th scope="col">Status</th> + <th scope="col">Komentar</th> + </tr> + <tr> + <td>{{SpecName('DOM WHATWG', "#dom-document-createelement", "Document.createElement")}}</td> + <td>{{Spec2('DOM WHATWG')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Kompabilitas_peramban">Kompabilitas peramban</h2> + +<p>{{CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Fitur</th> + <th>Chrome</th> + <th>Edge</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari (WebKit)</th> + </tr> + <tr> + <td>Dukungan dasar</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}<sup>[1][2]</sup></td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td>argumen <code>options</code></td> + <td>{{CompatVersionUnknown}}<sup>[3]</sup></td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoDesktop(50)}}<sup>[4][5]</sup></td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Fitur</th> + <th>Android</th> + <th>Android Webview</th> + <th>Edge</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Phone</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + <th>Chrome for Android</th> + </tr> + <tr> + <td>Dukungan dasar</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td>argumen <code>options</code></td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}<sup>[3]</sup></td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}<sup>[3]</sup></td> + </tr> + </tbody> +</table> +</div> + +<p>[1] Dimulai dengan Gecko 22.0 {{geckoRelease("22.0")}} <code>createElement()</code> tidak lagi menggunakan antarmuka {{domxref("HTMLSpanElement")}} ketika argumennya adalah "bgsounds", "multicol", atau "image". Sebagai gantinya, <code>HTMLUnknownElement</code> digunakan untuk "bgsound" dan "multicol" dan {{domxref("HTMLElement")}} <code>HTMLElement</code> digunakan untuk "image".</p> + +<p>[2] Implementasi Gecko dari <code>createElement</code> tidak sesuai dengan spesifikasi DOM untuk dokumen XUL dan XHTML: <code>localName</code> dan <code>namespaceURI</code> tidak diatur ke <code>null</code> pada elemen yang dibuat. Lihat {{ Bug(280692) }} untuk lebih jelasnya.</p> + +<p>[3] Pada versi sebelumnya dari spesifikasi, argumen ini hanyalah sebuah <em>string</em> yang nilainyaadalah nama tag elemen khusus. Misalnya bisa saja <code>document.createElement("button", "custom-button")</code> daripada <code>document.createElement("button", {is: "custom-button"})</code>. Demi kompabilitas ke belakang, Chrome menerima kedua bentuk tersebut, meskipun bentuk <em>string</em> sudah usang.</p> + +<p>[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, <code>options</code> harus sebuah objek.</p> + +<p>[5] Untuk eksperimen dengan elemen khusus di Firefox, Anda harus mengatur preferensi <code>dom.webcomponents.enabled</code> dan <code>dom.webcomponents.customelements.enabled</code> menjadi <code>true</code>.</p> + +<h3 id="Catatan_Quantum_CSS">Catatan Quantum CSS</h3> + +<ul> + <li>Pada Gecko, ketika Anda membuat sebuah <em>subtree </em>terpisah (misalnya sebuah {{htmlelement("div")}} dibuat menggunakan <code>createElement()</code> yang belum dimasukan ke dalam DOM), elemen akar <em>subtree </em>diatur sebagai sebuah elemen tingkat-blok. Pada Firefox mesin CSS paralel baru (yang dikenal dengan <a href="https://wiki.mozilla.org/Quantum">Quantum CSS</a> atau <a href="https://wiki.mozilla.org/Quantum/Stylo">Stylo</a>, direncanakan untuk dirilis pada Firefox 57), ini diatur sebagai <em>inline</em>, sesuai spesifikasi ({{bug(1374994)}}).</li> +</ul> + +<h2 id="See_also" name="See_also">Lihat juga</h2> + +<ul> + <li>{{domxref("Node.removeChild()")}}</li> + <li>{{domxref("Node.replaceChild()")}}</li> + <li>{{domxref("Node.appendChild()")}}</li> + <li>{{domxref("Node.insertBefore()")}}</li> + <li>{{domxref("Node.hasChildNodes()")}}</li> + <li>{{domxref("document.createElementNS()")}} — untuk secara eksplisit menentukan namespace URI untuk elemen.</li> +</ul> 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 +--- +<div>{{APIRef}}</div> + +<div> </div> + +<p>The <strong><code>Document</code></strong> interface represents any web page loaded in the browser and serves as an entry point into the web page's content, which is the <a href="/en-US/docs/Using_the_W3C_DOM_Level_1_Core" title="Using_the_W3C_DOM_Level_1_Core">DOM tree</a>. The DOM tree includes elements such as {{HTMLElement("body")}} and {{HTMLElement("table")}}, among <a href="/en-US/docs/Web/HTML/Element">many others</a>. It provides functionality which is global to the document, such as obtaining the page's URL and creating new elements in the document.</p> + +<p>{{inheritanceDiagram}}</p> + +<p>The <code>Document</code> interface describes the common properties and methods for any kind of document. Depending on the document's type (e.g. <a href="/en-US/docs/HTML" title="HTML">HTML</a>, <a href="/en-US/docs/XML" title="XML">XML</a>, SVG, …), a larger API is available: HTML documents, served with the <code>text/html</code> content type, also implement the {{domxref("HTMLDocument")}} interface, wherease SVG documents implement the {{domxref("SVGDocument")}} interface.</p> + +<h2 id="Properties" name="Properties">Properties</h2> + +<p><em>This interface also inherits from the {{domxref("Node")}} and {{domxref("EventTarget")}} interfaces.</em></p> + +<dl> + <dt>{{domxref("Document.all")}} {{Deprecated_inline}} {{non-standard_inline}}</dt> + <dd>Provides access to all elements with an <code>id</code>. This is a legacy, non-standard interface and you should use the {{domxref("document.getElementById()")}} method instead.</dd> + <dt>{{domxref("Document.async")}} {{Deprecated_inline}}</dt> + <dd>Used with {{domxref("Document.load")}} to indicate an asynchronous request.</dd> + <dt>{{domxref("Document.characterSet")}} {{readonlyinline}}</dt> + <dd>Returns the character set being used by the document.</dd> + <dt>{{domxref("Document.charset")}} {{readonlyinline}} {{Deprecated_inline}}</dt> + <dd>Alias of {{domxref("Document.characterSet")}}. Use this property instead.</dd> + <dt>{{domxref("Document.compatMode")}} {{readonlyinline}} {{experimental_inline}}</dt> + <dd>Indicates whether the document is rendered in <em>quirks</em> or <em>strict</em> mode.</dd> + <dt>{{domxref("Document.contentType")}} {{readonlyinline}} {{experimental_inline}}</dt> + <dd>Returns the Content-Type from the MIME Header of the current document.</dd> + <dt>{{domxref("Document.doctype")}} {{readonlyinline}}</dt> + <dd>Returns the Document Type Definition (DTD) of the current document.</dd> + <dt>{{domxref("Document.documentElement")}} {{readonlyinline}}</dt> + <dd>Returns the {{domxref("Element")}} that is a direct child of the document. For HTML documents, this is normally the HTML element.</dd> + <dt>{{domxref("Document.documentURI")}} {{readonlyinline}}</dt> + <dd>Returns the document location as a string.</dd> + <dt>{{domxref("Document.domConfig")}} {{Deprecated_inline}}</dt> + <dd>Should return a {{domxref("DOMConfiguration")}} object.</dd> + <dt>{{domxref("Document.fullscreen")}} {{obsolete_inline}}</dt> + <dd><code>true</code> when the document is in {{domxref("Using_full-screen_mode","full-screen mode")}}.</dd> + <dt>{{domxref("Document.hidden")}} {{readonlyinline}}</dt> + <dd>…</dd> + <dt>{{domxref("Document.implementation")}} {{readonlyinline}}</dt> + <dd>Returns the DOM implementation associated with the current document.</dd> + <dt>{{domxref("Document.inputEncoding")}} {{readonlyinline}} {{Deprecated_inline}}</dt> + <dd>Alias of {{domxref("Document.characterSet")}}. Use this property instead.</dd> + <dt>{{domxref("Document.lastStyleSheetSet")}} {{readonlyinline}}</dt> + <dd>Returns the name of the style sheet set that was last enabled. Has the value <code>null</code> until the style sheet is changed by setting the value of {{domxref("document.selectedStyleSheetSet","selectedStyleSheetSet")}}.</dd> + <dt>{{domxref("Document.mozSyntheticDocument")}} {{non-standard_inline}} {{gecko_minversion_inline("8.0")}}</dt> + <dd>Returns a {{jsxref("Boolean")}} that is <code>true</code> only if this document is synthetic, such as a standalone image, video, audio file, or the like.</dd> + <dt>{{domxref("Document.mozFullScreenElement")}} {{readonlyinline}} {{non-standard_inline}} {{gecko_minversion_inline("9.0")}}</dt> + <dd>The element that's currently in full screen mode for this document.</dd> + <dt>{{domxref("Document.mozFullScreenEnabled")}} {{readonlyinline}} {{non-standard_inline}} {{gecko_minversion_inline("9.0")}}</dt> + <dd><code>true</code> if calling {{domxref("Element.mozRequestFullscreen()")}} would succeed in the curent document.</dd> + <dt>{{domxref("Document.pointerLockElement")}} {{readonlyinline}} {{experimental_inline}}</dt> + <dd>Returns the element set as the target for mouse events while the pointer is locked. <code>null</code> if lock is pending, pointer is unlocked, or if the target is in another document.</dd> + <dt>{{domxref("Document.preferredStyleSheetSet")}} {{readonlyinline}}</dt> + <dd>Returns the preferred style sheet set as specified by the page author.</dd> + <dt>{{domxref("Document.scrollingElement")}} {{experimental_inline}} {{readonlyinline}}</dt> + <dd>Returns a reference to the {{domxref("Element")}} that scrolls the document.</dd> + <dt>{{domxref("Document.selectedStyleSheetSet")}}</dt> + <dd>Returns which style sheet set is currently in use.</dd> + <dt>{{domxref("Document.styleSheets")}} {{readonlyinline}}</dt> + <dd>Returns a list of the style sheet objects on the current document.</dd> + <dt>{{domxref("Document.styleSheetSets")}} {{readonlyinline}}</dt> + <dd>Returns a list of the style sheet sets available on the document.</dd> + <dt>{{domxref("Document.timeline")}} {{readonlyinline}}</dt> + <dd>…</dd> + <dt>{{domxref("Document.undoManager")}} {{readonlyinline}} {{experimental_inline}}</dt> + <dd>…</dd> + <dt>{{domxref("Document.URL")}} {{readonlyinline}}</dt> + <dd>Returns ...</dd> + <dt>{{domxref("Document.visibilityState")}} {{readonlyinline}}</dt> + <dd>…</dd> + <dt>{{domxref("Document.xmlEncoding")}} {{Deprecated_inline}}</dt> + <dd>Returns the encoding as determined by the XML declaration.</dd> + <dt>{{domxref("Document.xmlStandalone")}} {{obsolete_inline("10.0")}}</dt> + <dd>Returns <code>true</code> if the XML declaration specifies the document to be standalone (<em>e.g.,</em> An external part of the DTD affects the document's content), else <code>false</code>.</dd> + <dt>{{domxref("Document.xmlVersion")}} {{obsolete_inline("10.0")}}</dt> + <dd>Returns the version number as specified in the XML declaration or <code>"1.0"</code> if the declaration is absent.</dd> +</dl> + +<p>The <code>Document</code> interface is extended with the {{domxref("ParentNode")}} interface:</p> + +<p>{{page("/en-US/docs/Web/API/ParentNode","Properties")}}</p> + +<h3 id="Extension_for_HTML_document">Extension for HTML document</h3> + +<p><em>The <code>Document</code> interface for HTML documents inherits from the {{domxref("HTMLDocument")}} interface or, since HTML5, is extended for such documents.</em></p> + +<dl> + <dt>{{domxref("Document.activeElement")}} {{readonlyinline}}</dt> + <dd>Returns the currently focused element.</dd> + <dt>{{domxref("Document.alinkColor")}} {{Deprecated_inline}}</dt> + <dd>Returns or sets the color of active links in the document body.</dd> + <dt>{{domxref("Document.anchors")}}</dt> + <dd>Returns a list of all of the anchors in the document.</dd> + <dt>{{domxref("Document.applets")}} {{Deprecated_inline}}</dt> + <dd>Returns an ordered list of the applets within a document.</dd> + <dt>{{domxref("Document.bgColor")}} {{Deprecated_inline}}</dt> + <dd>Gets/sets the background color of the current document.</dd> + <dt>{{domxref("Document.body")}}</dt> + <dd>Returns the {{HTMLElement("body")}} element of the current document.</dd> + <dt>{{domxref("Document.cookie")}}</dt> + <dd>Returns a semicolon-separated list of the cookies for that document or sets a single cookie.</dd> + <dt>{{domxref("Document.defaultView")}} {{readonlyinline}}</dt> + <dd>Returns a reference to the window object.</dd> + <dt>{{domxref("Document.designMode")}}</dt> + <dd>Gets/sets the ability to edit the whole document.</dd> + <dt>{{domxref("Document.dir")}} {{readonlyinline}}</dt> + <dd>Gets/sets directionality (rtl/ltr) of the document.</dd> + <dt>{{domxref("Document.domain")}} {{readonlyinline}}</dt> + <dd>Returns the domain of the current document.</dd> + <dt>{{domxref("Document.embeds")}} {{readonlyinline}}</dt> + <dd>Returns a list of the embedded {{HTMLElement('embed')}} elements within the current document.</dd> + <dt>{{domxref("document.fgColor")}} {{Deprecated_inline}}</dt> + <dd>Gets/sets the foreground color, or text color, of the current document.</dd> + <dt>{{domxref("Document.forms")}} {{readonlyinline}}</dt> + <dd>Returns a list of the {{HTMLElement("form")}} elements within the current document.</dd> + <dt>{{domxref("Document.head")}} {{readonlyinline}}</dt> + <dd>Returns the {{HTMLElement("head")}} element of the current document.</dd> + <dt>{{domxref("Document.height")}} {{non-standard_inline}} {{obsolete_inline}}</dt> + <dd>Gets/sets the height of the current document.</dd> + <dt>{{domxref("Document.images")}} {{readonlyinline}}</dt> + <dd>Returns a list of the images in the current document.</dd> + <dt>{{domxref("Document.lastModified")}} {{readonlyinline}}</dt> + <dd>Returns the date on which the document was last modified.</dd> + <dt>{{domxref("Document.linkColor")}} {{Deprecated_inline}}</dt> + <dd>Gets/sets the color of hyperlinks in the document.</dd> + <dt>{{domxref("Document.links")}} {{readonlyinline}}</dt> + <dd>Returns a list of all the hyperlinks in the document.</dd> + <dt>{{domxref("Document.location")}} {{readonlyinline}}</dt> + <dd>Returns the URI of the current document.</dd> + <dt>{{domxref("Document.plugins")}} {{readonlyinline}}</dt> + <dd>Returns a list of the available plugins.</dd> + <dt>{{domxref("Document.readyState")}} {{readonlyinline}} {{gecko_minversion_inline("1.9.2")}}</dt> + <dd>Returns loading status of the document.</dd> + <dt>{{domxref("Document.referrer")}} {{readonlyinline}}</dt> + <dd>Returns the URI of the page that linked to this page.</dd> + <dt>{{domxref("Document.scripts")}} {{readonlyinline}}</dt> + <dd>Returns all the {{HTMLElement("script")}} elements on the document.</dd> + <dt>{{domxref("Document.title")}}</dt> + <dd>Sets or gets title of the current document.</dd> + <dt>{{domxref("Document.URL")}} {{readonlyInline}}</dt> + <dd>Returns<span style="line-height: 19.0909080505371px;"> the document location as a string.</span></dd> + <dt>{{domxref("Document.vlinkColor")}} {{Deprecated_inline}}</dt> + <dd>Gets/sets the color of visited hyperlinks.</dd> + <dt>{{domxref("Document.width")}} {{non-standard_inline}} {{obsolete_inline}}</dt> + <dd>Returns the width of the current document.</dd> +</dl> + +<h3 id="Event_handlers" name="Event_handlers">Event handlers</h3> + +<dl> + <dt>{{domxref("GlobalEventHandlers.onabort")}}</dt> + <dd>Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("abort")}} event is raised.</dd> + <dt>{{domxref("Document.onafterscriptexecute")}} {{non-standard_inline}}</dt> + <dd>Represents the event handling code for the {{event("afterscriptexecute")}} event.</dd> + <dt>{{domxref("Document.onbeforescriptexecute")}} {{non-standard_inline}}</dt> + <dd>Represents the event handling code for the {{event("beforescriptexecute")}} event.</dd> + <dt>{{domxref("GlobalEventHandlers.onblur")}}</dt> + <dd>Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("blur")}} event is raised.</dd> + <dt>{{domxref("GlobalEventHandlers.oncancel")}}</dt> + <dd>Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("cancel")}} event is raised.</dd> + <dt>{{domxref("GlobalEventHandlers.oncanplay")}}</dt> + <dd>Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("canplay")}} event is raised.</dd> + <dt>{{domxref("GlobalEventHandlers.oncanplaythrough")}}</dt> + <dd>Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("canplaythrough")}} event is raised.</dd> + <dt>{{domxref("GlobalEventHandlers.onchange")}}</dt> + <dd>Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("change")}} event is raised.</dd> + <dt>{{domxref("GlobalEventHandlers.onclick")}}</dt> + <dd>Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("click")}} event is raised.</dd> + <dt>{{domxref("GlobalEventHandlers.onclose")}}</dt> + <dd>Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("close")}} event is raised.</dd> + <dt>{{domxref("GlobalEventHandlers.oncontextmenu")}}</dt> + <dd>Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("contextmenu")}} event is raised.</dd> + <dt>{{domxref("Document.oncopy")}} {{non-standard_inline}}</dt> + <dd>Represents the event handling code for the {{event("copy")}} event.</dd> + <dt>{{domxref("GlobalEventHandlers.oncuechange")}}</dt> + <dd>Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("cuechange")}} event is raised.</dd> + <dt>{{domxref("Document.oncut")}} {{non-standard_inline}}</dt> + <dd>Represents the event handling code for the {{event("cut")}} event.</dd> + <dt>{{domxref("GlobalEventHandlers.ondblclick")}}</dt> + <dd>Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("dblclick")}} event is raised.</dd> + <dt>{{domxref("GlobalEventHandlers.ondrag")}}</dt> + <dd>Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("drag")}} event is raised.</dd> + <dt>{{domxref("GlobalEventHandlers.ondragend")}}</dt> + <dd>Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("dragend")}} event is raised.</dd> + <dt>{{domxref("GlobalEventHandlers.ondragenter")}}</dt> + <dd>Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("dragenter")}} event is raised.</dd> + <dt>{{domxref("GlobalEventHandlers.ondragexit")}}</dt> + <dd>Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("dragexit")}} event is raised.</dd> + <dt>{{domxref("GlobalEventHandlers.ondragleave")}}</dt> + <dd>Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("dragleave")}} event is raised.</dd> + <dt>{{domxref("GlobalEventHandlers.ondragover")}}</dt> + <dd>Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("dragover")}} event is raised.</dd> + <dt>{{domxref("GlobalEventHandlers.ondragstart")}}</dt> + <dd>Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("dragstart")}} event is raised.</dd> + <dt>{{domxref("GlobalEventHandlers.ondrop")}}</dt> + <dd>Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("drop")}} event is raised.</dd> + <dt>{{domxref("GlobalEventHandlers.ondurationchange")}}</dt> + <dd>Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("durationchange")}} event is raised.</dd> + <dt>{{domxref("GlobalEventHandlers.onemptied")}}</dt> + <dd>Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("emptied")}} event is raised.</dd> + <dt>{{domxref("GlobalEventHandlers.onended")}}</dt> + <dd>Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("ended")}} event is raised.</dd> + <dt>{{domxref("GlobalEventHandlers.onerror")}}</dt> + <dd>Is an {{domxref("OnErrorEventHandler")}} representing the code to be called when the {{event("error")}} event is raised.</dd> + <dt>{{domxref("GlobalEventHandlers.onfocus")}}</dt> + <dd>Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("focus")}} event is raised.</dd> + <dt>{{domxref("Document.onfullscreenchange")}}</dt> + <dd>Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("fullscreenchange")}} event is raised.</dd> + <dt>{{domxref("Document.onfullscreenerror")}}</dt> + <dd>Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("fullscreenerror")}} event is raised.</dd> + <dt>{{domxref("GlobalEventHandlers.oninput")}}</dt> + <dd>Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("input")}} event is raised.</dd> + <dt>{{domxref("GlobalEventHandlers.oninvalid")}}</dt> + <dd>Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("invalid")}} event is raised.</dd> + <dt>{{domxref("GlobalEventHandlers.onkeydown")}}</dt> + <dd>Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("keydown")}} event is raised.</dd> + <dt>{{domxref("GlobalEventHandlers.onkeypress")}}</dt> + <dd>Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("keypress")}} event is raised.</dd> + <dt>{{domxref("GlobalEventHandlers.onkeyup")}}</dt> + <dd>Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("keyup")}} event is raised.</dd> + <dt>{{domxref("GlobalEventHandlers.onload")}}</dt> + <dd>Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("load")}} event is raised.</dd> + <dt>{{domxref("GlobalEventHandlers.onloadeddata")}}</dt> + <dd>Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("loadeddata")}} event is raised.</dd> + <dt>{{domxref("GlobalEventHandlers.onloadedmetadata")}}</dt> + <dd>Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("loadedmetadata")}} event is raised.</dd> + <dt>{{domxref("GlobalEventHandlers.onloadstart")}}</dt> + <dd>Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("loadstart")}} event is raised.</dd> + <dt>{{domxref("GlobalEventHandlers.onmousedown")}}</dt> + <dd>Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("mousedown")}} event is raised.</dd> + <dt>{{domxref("GlobalEventHandlers.onmouseenter")}}</dt> + <dd>Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("mouseenter")}} event is raised.</dd> + <dt>{{domxref("GlobalEventHandlers.onmouseleave")}}</dt> + <dd>Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("mouseleave")}} event is raised.</dd> + <dt>{{domxref("GlobalEventHandlers.onmousemove")}}</dt> + <dd>Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("mousemove")}} event is raised.</dd> + <dt>{{domxref("GlobalEventHandlers.onmouseout")}}</dt> + <dd>Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("mouseout")}} event is raised.</dd> + <dt>{{domxref("GlobalEventHandlers.onmouseover")}}</dt> + <dd>Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("mouseover")}} event is raised.</dd> + <dt>{{domxref("GlobalEventHandlers.onmouseup")}}</dt> + <dd>Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("mouseup")}} event is raised.</dd> + <dt>{{domxref("GlobalEventHandlers.onmousewheel")}}</dt> + <dd>Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("mousewheel")}} event is raised.</dd> + <dt>{{domxref("GlobalEventHandlers.onpause")}}</dt> + <dd>Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("pause")}} event is raised.</dd> + <dt>{{domxref("Document.onpaste")}} {{non-standard_inline}}</dt> + <dd>Represents the event handling code for the {{event("paste")}} event.</dd> + <dt>{{domxref("GlobalEventHandlers.onplay")}}</dt> + <dd>Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("play")}} event is raised.</dd> + <dt>{{domxref("GlobalEventHandlers.onplaying")}}</dt> + <dd>Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("playing")}} event is raised.</dd> + <dt>{{domxref("GlobalEventHandlers.onpointerdown")}}</dt> + <dd>Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("pointerdown")}} event is raised.</dd> + <dt>{{domxref("Document.onpointerlockchange")}} {{experimental_inline}}</dt> + <dd>Represents the event handling code for the {{event("pointerlockchange")}} event.</dd> + <dt>{{domxref("Document.onpointerlockerror")}} {{experimental_inline}}</dt> + <dd>Represetnts the event handling code for the {{event("pointerlockerror")}} event.</dd> + <dt>{{domxref("GlobalEventHandlers.onpointermove")}}</dt> + <dd>Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("pointermove")}} event is raised.</dd> + <dt>{{domxref("GlobalEventHandlers.onpointerup")}}</dt> + <dd>Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("pointerup")}} event is raised.</dd> + <dt>{{domxref("GlobalEventHandlers.onpointercancel")}}</dt> + <dd>Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("pointercancel")}} event is raised.</dd> + <dt>{{domxref("GlobalEventHandlers.onpointerover")}}</dt> + <dd>Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("pointerover")}} event is raised.</dd> + <dt>{{domxref("GlobalEventHandlers.onpointerout")}}</dt> + <dd>Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("pointerout")}} event is raised.</dd> + <dt>{{domxref("GlobalEventHandlers.onpointerenter")}}</dt> + <dd>Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("pointerevent")}} event is raised.</dd> + <dt>{{domxref("GlobalEventHandlers.onpointerleave")}}</dt> + <dd>Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("pointerleave")}} event is raised.</dd> + <dt>{{domxref("GlobalEventHandlers.onpointerlockchange")}} {{experimental_inline}}</dt> + <dd>Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("pointerlockchange")}} event is raised.</dd> + <dt>{{domxref("GlobalEventHandlers.onpointerlockerror")}} {{experimental_inline}}</dt> + <dd>Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("pointerlockerror")}} event is raised.</dd> + <dt>{{domxref("GlobalEventHandlers.onprogress")}}</dt> + <dd>Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("progress")}} event is raised.</dd> + <dt>{{domxref("GlobalEventHandlers.onratechange")}}</dt> + <dd>Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("ratechange")}} event is raised.</dd> + <dt>{{domxref("Document.onreadystatechange")}} {{gecko_minversion_inline("1.9.2")}}</dt> + <dd>Represents the event handling code for the {{event("readystatechange")}} event.</dd> + <dt>{{domxref("GlobalEventHandlers.onreset")}}</dt> + <dd>Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("reset")}} event is raised.</dd> + <dt>{{domxref("GlobalEventHandlers.onscroll")}}</dt> + <dd>Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("scroll")}} event is raised.</dd> + <dt>{{domxref("GlobalEventHandlers.onseeked")}}</dt> + <dd>Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("seeked")}} event is raised.</dd> + <dt>{{domxref("GlobalEventHandlers.onseeking")}}</dt> + <dd>Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("seeking")}} event is raised.</dd> + <dt>{{domxref("GlobalEventHandlers.onselect")}}</dt> + <dd>Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("select")}} event is raised.</dd> + <dt>{{domxref("GlobalEventHandlers.onselectstart")}}</dt> + <dd>Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("selectstart")}} event is raised.</dd> + <dt>{{domxref("Document.onselectionchange")}}</dt> + <dd>Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("selectionchange")}} event is raised.</dd> + <dt>{{domxref("GlobalEventHandlers.onshow")}}</dt> + <dd>Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("show")}} event is raised.</dd> + <dt>{{domxref("GlobalEventHandlers.onsort")}} {{experimental_inline}}</dt> + <dd>Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("sort")}} event is raised.</dd> + <dt>{{domxref("GlobalEventHandlers.onstalled")}}</dt> + <dd>Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("stalled")}} event is raised.</dd> + <dt>{{domxref("GlobalEventHandlers.onsubmit")}}</dt> + <dd>Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("submit")}} event is raised.</dd> + <dt>{{domxref("GlobalEventHandlers.onsuspend")}}</dt> + <dd>Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("suspend")}} event is raised.</dd> + <dt>{{domxref("GlobalEventHandlers.ontimeupdate")}}</dt> + <dd>Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("timeupdate")}} event is raised.</dd> + <dt>{{domxref("GlobalEventHandlers.onvolumechange")}}</dt> + <dd>Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("volumechange")}} event is raised.</dd> + <dt>{{domxref("GlobalEventHandlers.onwaiting")}}</dt> + <dd>Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("waiting")}} event is raised.</dd> + <dt>{{domxref("Document.onwheel")}} {{non-standard_inline}}</dt> + <dd>Represents the event handling code for the {{event("wheel")}} event.</dd> +</dl> + +<h2 id="Methods" name="Methods">Methods</h2> + +<p><em>This interface also inherits from the {{domxref("Node")}} and {{domxref("EventTarget")}} interfaces.</em></p> + +<dl> + <dt>{{domxref("Document.adoptNode()")}}</dt> + <dd>Adopt node from an external document.</dd> + <dt>{{domxref("Document.captureEvents()")}} {{Deprecated_inline}}</dt> + <dd>See {{domxref("Window.captureEvents")}}.</dd> + <dt>{{domxref("Document.caretPositionFromPoint()")}}{{experimental_inline}}</dt> + <dd>Gets the {{domxref("CaretPosition")}} at or near the specified coordinates.</dd> + <dt>{{domxref("Document.caretRangeFromPoint()")}}{{non-standard_inline}}</dt> + <dd>Gets a {{Domxref("Range")}} object for the document fragment under the specified coordinates.</dd> + <dt>{{domxref("Document.createAttribute()")}}</dt> + <dd>Creates a new {{domxref("Attr")}} object and returns it.</dd> + <dt>{{domxref("Document.createAttributeNS()")}}</dt> + <dd>Creates a new attribute node in a given namespace and returns it.</dd> + <dt>{{domxref("Document.createCDATASection()")}}</dt> + <dd>Creates a new CDATA node and returns it.</dd> + <dt>{{domxref("Document.createComment()")}}</dt> + <dd>Creates a new comment node and returns it.</dd> + <dt>{{domxref("Document.createDocumentFragment()")}}</dt> + <dd>Creates a new document fragment.</dd> + <dt>{{domxref("Document.createElement()")}}</dt> + <dd>Creates a new element with the given tag name.</dd> + <dt>{{domxref("Document.createElementNS()")}}</dt> + <dd>Creates a new element with the given tag name and namespace URI.</dd> + <dt>{{domxref("Document.createEntityReference()")}} {{obsolete_inline}}</dt> + <dd>Creates a new entity reference object and returns it.</dd> + <dt>{{domxref("Document.createEvent()")}}</dt> + <dd>Creates an event object.</dd> + <dt>{{domxref("Document.createNodeIterator()")}}</dt> + <dd>Creates a {{domxref("NodeIterator")}} object.</dd> + <dt>{{domxref("Document.createProcessingInstruction()")}}</dt> + <dd>Creates a new {{domxref("ProcessingInstruction")}} object.</dd> + <dt>{{domxref("Document.createRange()")}}</dt> + <dd>Creates a {{domxref("Range")}} object.</dd> + <dt>{{domxref("Document.createTextNode()")}}</dt> + <dd>Creates a text node.</dd> + <dt>{{domxref("Document.createTouch()")}}</dt> + <dd>Creates a {{domxref("Touch")}} object.</dd> + <dt>{{domxref("Document.createTouchList()")}}</dt> + <dd>Creates a {{domxref("TouchList")}} object.</dd> + <dt>{{domxref("Document.createTreeWalker()")}}</dt> + <dd>Creates a {{domxref("TreeWalker")}} object.</dd> + <dt>{{domxref("Document.elementFromPoint()")}}{{experimental_inline}}</dt> + <dd>Returns the topmost element at the specified coordinates. </dd> + <dt>{{domxref("Document.elementsFromPoint()")}}{{experimental_inline}}</dt> + <dd>Returns an array of all elements at the specified coordinates.</dd> + <dt>{{domxref("Document.enableStyleSheetsForSet()")}}</dt> + <dd>Enables the style sheets for the specified style sheet set.</dd> + <dt>{{domxref("Document.exitPointerLock()")}} {{experimental_inline}}</dt> + <dd>Release the pointer lock.</dd> + <dt>{{domxref("Document.getAnimations()")}} {{experimental_inline}}</dt> + <dd>Returns an array of all {{domxref("Animation")}} objects currently in effect whose target elements are descendants of the <code>document</code>.</dd> + <dt>{{domxref("Document.getElementsByClassName()")}}</dt> + <dd>Returns a list of elements with the given class name.</dd> + <dt>{{domxref("Document.getElementsByTagName()")}}</dt> + <dd>Returns a list of elements with the given tag name.</dd> + <dt>{{domxref("Document.getElementsByTagNameNS()")}}</dt> + <dd>Returns a list of elements with the given tag name and namespace.</dd> + <dt>{{domxref("Document.importNode()")}}</dt> + <dd>Returns a clone of a node from an external document.</dd> + <dt>{{domxref("Document.normalizeDocument()")}} {{obsolete_inline}}</dt> + <dd>Replaces entities, normalizes text nodes, etc.</dd> + <dt>{{domxref("Document.registerElement()")}} {{experimental_inline}}</dt> + <dd>Registers a web component.</dd> + <dt>{{domxref("Document.releaseCapture()")}} {{non-standard_inline}} {{gecko_minversion_inline("2.0")}}</dt> + <dd>Releases the current mouse capture if it's on an element in this document.</dd> + <dt>{{domxref("Document.releaseEvents()")}} {{non-standard_inline}} {{Deprecated_inline}}</dt> + <dd>See {{domxref("Window.releaseEvents()")}}.</dd> + <dt>{{domxref("Document.routeEvent()")}} {{non-standard_inline}} {{obsolete_inline(24)}}</dt> + <dd>See {{domxref("Window.routeEvent()")}}.</dd> + <dt>{{domxref("Document.mozSetImageElement()")}} {{non-standard_inline}} {{gecko_minversion_inline("2.0")}}</dt> + <dd>Allows you to change the element being used as the background image for a specified element ID.</dd> +</dl> + +<p>The <code>Document</code> interface is extended with the {{domxref("ParentNode")}} interface:</p> + +<dl> + <dt>{{domxref("document.getElementById","document.getElementById(String id)")}}</dt> + <dd>Returns an object reference to the identified element.</dd> + <dt>{{domxref("document.querySelector","document.querySelector(String selector)")}} {{gecko_minversion_inline("1.9.1")}}</dt> + <dd>Returns the first Element node within the document, in document order, that matches the specified selectors.</dd> + <dt>{{domxref("document.querySelectorAll","document.querySelectorAll(String selector)")}} {{gecko_minversion_inline("1.9.1")}}</dt> + <dd>Returns a list of all the Element nodes within the document that match the specified selectors.</dd> +</dl> + +<p>The <code>Document</code> interface is extended with the {{domxref("XPathEvaluator")}} interface:</p> + +<dl> + <dt>{{domxref("document.createExpression","document.createExpression(String expression, XPathNSResolver resolver)")}}</dt> + <dd>Compiles an <code><a href="/en-US/docs/XPathExpression" title="XPathExpression">XPathExpression</a></code> which can then be used for (repeated) evaluations.</dd> + <dt>{{domxref("document.createNSResolver","document.createNSResolver(Node resolver)")}}</dt> + <dd>Creates an {{domxref("XPathNSResolver")}} object.</dd> + <dt>{{domxref("document.evaluate","document.evaluate(String expression, Node contextNode, XPathNSResolver resolver, Number type, Object result)")}}</dt> + <dd>Evaluates an XPath expression.</dd> +</dl> + +<h3 id="Extension_for_HTML_documents">Extension for HTML documents</h3> + +<p>The <code>Document</code> interface for HTML documents inherit from the {{domxref("HTMLDocument")}} interface or, since HTML5, is extended for such documents:</p> + +<dl> + <dt>{{domxref("document.clear()")}} {{non-standard_inline}} {{Deprecated_inline}}</dt> + <dd>In majority of modern browsers, including recent versions of Firefox and Internet Explorer, this method does nothing.</dd> + <dt>{{domxref("document.close()")}}</dt> + <dd>Closes a document stream for writing.</dd> + <dt>{{domxref("document.execCommand","document.execCommand(String command[, Boolean showUI[, String value]])")}}</dt> + <dd>On an editable document, executes a formating command.</dd> + <dt>{{domxref("document.getElementsByName","document.getElementsByName(String name)")}}</dt> + <dd>Returns a list of elements with the given name.</dd> + <dt>{{domxref("document.getSelection()")}}</dt> + <dd>Returns a {{domxref("Selection")}} object related to text selected in the document.</dd> + <dt>{{domxref("document.hasFocus()")}}</dt> + <dd>Returns <code>true</code> if the focus is currently located anywhere inside the specified document.</dd> + <dt>{{domxref("document.open()")}}</dt> + <dd>Opens a document stream for writing.</dd> + <dt>{{domxref("document.queryCommandEnabled","document.queryCommandEnabled(String command)")}}</dt> + <dd>Returns true if the formating command can be executed on the current range.</dd> + <dt>{{domxref("document.queryCommandIndeterm","document.queryCommandIndeterm(String command)")}}</dt> + <dd>Returns true if the formating command is in an indeterminate state on the current range.</dd> + <dt>{{domxref("document.queryCommandState","document.queryCommandState(String command)")}}</dt> + <dd>Returns true if the formating command has been executed on the current range.</dd> + <dt>{{domxref("document.queryCommandSupported","document.queryCommandSupported(String command)")}}</dt> + <dd>Returns true if the formating command is supported on the current range.</dd> + <dt>{{domxref("document.queryCommandValue","document.queryCommandValue(String command)")}}</dt> + <dd>Returns the current value of the current range for a formating command.</dd> + <dt>{{domxref("document.write","document.write(String text)")}}</dt> + <dd>Writes text in a document.</dd> + <dt>{{domxref("document.writeln","document.writeln(String text)")}}</dt> + <dd>Writes a line of text in a document.</dd> +</dl> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('Selection API', '', 'Extend Document and GlobalEventHandlers')}}</td> + <td>{{Spec2('Selection API')}}</td> + <td>Adds <code>onselectstart</code> and <code>onselectionchange</code>.</td> + </tr> + <tr> + <td>{{SpecName('DOM1','#i-Document','Document')}}</td> + <td>{{Spec2('DOM1')}}</td> + <td>Initial definition for the interface</td> + </tr> + <tr> + <td>{{SpecName('DOM2 Core','#i-Document','Document')}}</td> + <td>{{Spec2('DOM2 Core')}}</td> + <td>Supersede DOM 1</td> + </tr> + <tr> + <td>{{SpecName('DOM3 Core','#i-Document','Document')}}</td> + <td>{{Spec2('DOM3 Core')}}</td> + <td>Supersede DOM 2</td> + </tr> + <tr> + <td>{{SpecName('DOM WHATWG','#interface-document','Document')}}</td> + <td>{{Spec2('DOM WHATWG')}}</td> + <td>Intend to supersede DOM 3</td> + </tr> + <tr> + <td>{{SpecName('HTML WHATWG','dom.html#the-document-object','Document')}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td>Turn the {{domxref("HTMLDocument")}} interface into a <code>Document</code> extension.</td> + </tr> + <tr> + <td>{{SpecName('DOM3 XPath','xpath.html#XPathEvaluator','XPathEvaluator')}}</td> + <td>{{Spec2('DOM3 XPath')}}</td> + <td>Define the {{domxref("XPathEvaluator")}} interface which extend document.</td> + </tr> + <tr> + <td>{{SpecName('HTML Editing','#dom-document-getselection','Document')}}</td> + <td>{{Spec2('HTML Editing')}}</td> + <td>Extend the <code>Document</code> interface</td> + </tr> + <tr> + <td>{{SpecName('CSSOM View','#extensions-to-the-document-interface','Document')}}</td> + <td>{{Spec2('CSSOM View')}}</td> + <td>Extend the <code>Document</code> interface</td> + </tr> + <tr> + <td>{{SpecName('CSSOM','#extensions-to-the-document-interface','Document')}}</td> + <td>{{Spec2('CSSOM')}}</td> + <td>Extend the <code>Document</code> interface</td> + </tr> + <tr> + <td>{{SpecName('Pointer Lock','#extensions-to-the-document-interface','Document')}}</td> + <td>{{Spec2('Pointer Lock')}}</td> + <td>Extend the <code>Document</code> interface</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility_notes">Browser compatibility notes</h2> + +<h3 id="Firefox_notes">Firefox notes</h3> + +<p>Mozilla defines a set of non-standard properties made only for XUL content:</p> + +<dl> + <dt>{{domxref("document.currentScript")}} {{non-standard_inline}} {{gecko_minversion_inline("2.0")}}</dt> + <dd>Returns the {{HTMLElement("script")}} element that is currently executing.</dd> + <dt>{{domxref("document.documentURIObject")}} {{gecko_minversion_inline("1.9")}}</dt> + <dd>(<strong>Mozilla add-ons only!</strong>) Returns the {{Interface("nsIURI")}} object representing the URI of the document. This property only has special meaning in privileged JavaScript code (with UniversalXPConnect privileges).</dd> + <dt>{{domxref("document.popupNode")}}</dt> + <dd>Returns the node upon which a popup was invoked.</dd> + <dt>{{domxref("document.tooltipNode")}}</dt> + <dd>Returns the node which is the target of the current tooltip.</dd> +</dl> + +<p>Mozilla also define some non-standard methods:</p> + +<dl> + <dt>{{domxref("document.execCommandShowHelp")}} {{obsolete_inline("14.0")}}</dt> + <dd>This method never did anything and always threw an exception, so it was removed in Gecko 14.0 {{geckoRelease("14.0")}}.</dd> + <dt>{{domxref("document.getBoxObjectFor")}} {{obsolete_inline}}</dt> + <dd>Use the {{domxref("Element.getBoundingClientRect()")}} method instead.</dd> + <dt>{{domxref("document.loadOverlay")}} {{Fx_minversion_inline("1.5")}}</dt> + <dd>Loads a <a href="/en-US/docs/XUL_Overlays" title="XUL_Overlays">XUL overlay</a> dynamically. This only works in XUL documents.</dd> + <dt>{{domxref("document.queryCommandText")}} {{obsolete_inline("14.0")}}</dt> + <dd>This method never did anything but throw an exception, and was removed in Gecko 14.0 {{geckoRelease("14.0")}}.</dd> +</dl> + +<h3 id="Internet_Explorer_notes">Internet Explorer notes</h3> + +<p>Microsoft defines some non-standard properties:</p> + +<dl> + <dt>{{domxref("document.fileSize")}}* {{non-standard_inline}} {{obsolete_inline}}</dt> + <dd>Returns size in bytes of the document. Starting with Internet Explorer 11, that property is no longer supported. See <a href="http://msdn.microsoft.com/en-us/library/ms533752%28v=VS.85%29.aspx" title="http://msdn.microsoft.com/en-us/library/ms533752%28v=VS.85%29.aspx">MSDN</a>.</dd> + <dt><span style="font-weight: normal; line-height: 1.5;">Internet Explorer does not support all methods from the <code>Node</code> interface in the <code>Document</code> interface:</span></dt> +</dl> + +<dl> + <dt>{{domxref("document.contains")}}</dt> + <dd>As a work-around, <code>document.body.contains()</code> can be used.</dd> +</dl> + +<p> </p> 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 +--- +<p>{{ APIRef("DOM") }}</p> + +<p>Properti <code>links</code> mengembalikan sebuah collection dari semua elemen {{HTMLElement("area")}} dan elemen {{HTMLElement("a")}} pada sebuah dokumen dengan sebuah nilai pada atribut <a href="/en-US/docs/Web/API/URLUtils.href">href</a> .</p> + +<h2 id="Syntax" name="Syntax">Sintaks</h2> + +<pre class="eval"><em>nodeList</em> = document.links +</pre> + +<h2 id="Example" name="Example">Contoh</h2> + +<pre class="brush: js">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); +} +</pre> + +<h2 id="Spesifikasi">Spesifikasi</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Spesifikasi</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('HTML WHATWG', '#dom-document-links', 'Document.links')}}</td> + <td>{{ Spec2('HTML WHATWG') }}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName("DOM2 HTML", "html.html#ID-7068919", "document.links")}}</td> + <td>{{Spec2("DOM2 HTML")}}</td> + <td>Initial definition</td> + </tr> + </tbody> +</table> + +<h2 id="Kompabilitas_browser">Kompabilitas browser</h2> + +<p>{{ CompatibilityTable() }}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari (WebKit)</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Phone</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + </tr> + </tbody> +</table> +</div> 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 +--- +<div>{{ ApiRef("DOM") }}</div> + +<p>Menuliskan teks string ke sebuah dokumen stream yang dibuka dengan <a href="/en-US/docs/Web/API/document.open">document.open()</a>.</p> + +<div class="note">Catatan: ketika <code>document.write</code> menulis ke dokumen <strong>stream</strong>, memanggil <code>document.write</code> pada sebuah dokumen tertutup (termuat), dokumen secara otomatis memanggil <code>document.open</code>, <a href="https://developer.mozilla.org/en-US/docs/Web/API/document.open#Notes">yang akan menghapus dokumen</a>.</div> + +<h2 id="Sintaks">Sintaks</h2> + +<pre class="brush: js">document.write(<em>markup</em>); +</pre> + +<p><code>markup</code> merupakan sebuah string yang berisi teks untuk ditulis ke dalam dokumen.</p> + +<h3 id="Contoh">Contoh</h3> + +<pre class="brush: html"><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> +</pre> + +<h2 id="Catatan">Catatan</h2> + +<p>Menulis ke sebuah dokumen yang telah dimuat tanpa memanggil <a href="/id/docs/Web/API/document.open"><code>document.open()</code></a> akan secara otomatis melakukan panggilan <code>document.open</code>. Setelah selesai menulis, disarankan untuk memanggil <a href="/en-US/docs/Web/API/document.close"><code>document.close()</code></a>, untuk meminta browser untuk menyelesaikan memuat halaman. Teks yang anda tulis akan di parse ke dalam stuktur model dokumen tersebut. Pada contoh diatas, elemen <code>h1</code> menjadi sebuah node pada document.</p> + +<p>Jika pemanggilan <code>document.write()</code> merpakan embeded pada inline tag html <code><script></code> tag, maka tidak akan memanggil <code>document.open()</code>. Sebagai contoh:</p> + +<pre class="brush: html"><script> + document.write("<h1>Main title</h1>") +</script> +</pre> + +<div class="note"><strong>Catatan:</strong> <code>document.write</code> an <code>document.writeln</code> <a href="/en-US/docs/Archive/Web/Writing_JavaScript_for_HTML">tidak berfungsi di dokumen XHTML</a> ( anda akan mendapat peringatan "Operation is not supported" [<code>NS_ERROR_DOM_NOT_SUPPORTED_ERR</code>] error pada konsole). Ini terjadi ketika membuka sebuah file lokal dengan ekstensi file .xhtml atau dokumen lain yang disajikan dengan <a href="/en-US/docs/Glossary/MIME_type">MIME type</a> <code>application/xhtml+xml</code> . Informasi lengkap tersedia di <a class="external" href="http://www.w3.org/MarkUp/2004/xhtml-faq#docwrite">W3C XHTML FAQ</a>.</div> + +<div class="note"><strong>Catatan:</strong> <code>document.write</code> pada script <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script#attr-defer">deferred</a> atau <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script#attr-async">asynchronous</a> akan diabaikan, dan anda mendapatkan peringatan error "A call to <code>document.write()</code> from an asynchronously-loaded external script was ignored" pada konsole.</div> + +<h2 id="Spesifikasi">Spesifikasi</h2> + +<ul> + <li><a class="external" href="http://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-75233634">DOM Level 2 HTML: <code>write()</code> Method</a></li> + <li><a class="external" href="http://www.w3.org/TR/2011/WD-html5-author-20110705/apis-in-html-documents.html#dynamic-markup-insertion">Dynamic markup insertion in HTML</a></li> +</ul> + +<h2 id="Lihat_juga">Lihat juga</h2> + +<ul> + <li>{{ domxref("element.innerHTML") }}</li> + <li>{{ domxref("document.createElement()") }}</li> +</ul> 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 +--- +<p>{{APIRef("DOM")}}</p> + +<p>Mengidentifikasi event untuk target saat ini, seperti ketika event melalui DOM. Event tersebut selalu mengacu kepada lemen yang terikat dengan <em>event handler</em>, sebagai lawan dari <code>event.target</code> yang mana mengidentifikasi elemen ketika event tersebut terjadi.</p> + +<h2 id="Contoh">Contoh</h2> + +<p><code>event.currentTarget</code> sangat menarik untuk digunakan ketika menyatukan event handler yang sama ke beberapa element.</p> + +<pre class="brush: js">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 +</pre> + +<h2 id="Spesifikasi">Spesifikasi</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th>Spesifikasi</th> + <th>Status</th> + <th>Komentar</th> + </tr> + <tr> + <td>{{SpecName("DOM WHATWG", "#dom-event-currenttarget", "Event.currentTarget")}}</td> + <td>{{Spec2("DOM WHATWG")}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName("DOM4", "#dom-event-currenttarget", "Event.currentTarget")}}</td> + <td>{{Spec2("DOM4")}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName("DOM3 Events", "#dfn-current-event-target", "current event target")}}</td> + <td>{{Spec2("DOM3 Events")}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName("DOM2 Events", "#Events-Event-currentTarget", "Event.currentTarget")}}</td> + <td>{{Spec2("DOM2 Events")}}</td> + <td>Definisi awal</td> + </tr> + </tbody> +</table> + +<h2 id="Kesesuaian_browser">Kesesuaian browser</h2> + +<p>{{CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Edge</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}<sup>[1]</sup></td> + <td>{{CompatVersionUnknown}}</td> + <td>10.0</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Edge</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>10.0</td> + </tr> + </tbody> +</table> +</div> + +<p>[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 <code>event.currentTarget</code> dan <code>this</code> adalah objek global. Satu solusin untuk meniru fitur <code>event.currentTarget</code> adalah dengan cara membungkus handler anda di dalam fungsi memanggil handler tersebut menggunakan <code>Function.prototype.call</code> dengan elemen sebagai argumen awal. Dengan cara ini, <code>this</code> akan menampilkan hasil yang diharapkan.</p> + +<h2 id="Lihat_juga">Lihat juga</h2> + +<p><a href="/en-US/docs/Web/API/Event/Comparison_of_Event_Targets">Perbandingan dari Event Targets</a></p> 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 +--- +<p>{{APIRef("DOM")}}</p> + +<p>Antarmuka <code><strong>Event</strong></code> mewakili setiap event pada DOM. mengandung properti umum dan method ke setiap event.</p> + +<p>Banyak sekali antarmuka lain yang menginplementasikan antarmuka <code>Event</code>, baik secara langsung atau dengan mengimplementsikan antarmuka lain dimana diantaranya:</p> + +<div class="index"> +<ul> + <li>{{domxref("AnimationEvent")}}</li> + <li>{{domxref("AudioProcessingEvent")}}</li> + <li>{{domxref("BeforeInputEvent")}}</li> + <li>{{domxref("BeforeUnloadEvent")}}</li> + <li>{{domxref("BlobEvent")}}</li> + <li>{{domxref("ClipboardEvent")}}</li> + <li>{{domxref("CloseEvent")}}</li> + <li>{{domxref("CompositionEvent")}}</li> + <li>{{domxref("CSSFontFaceLoadEvent")}}</li> + <li>{{domxref("CustomEvent")}}</li> + <li>{{domxref("DeviceLightEvent")}}</li> + <li>{{domxref("DeviceMotionEvent")}}</li> + <li>{{domxref("DeviceOrientationEvent")}}</li> + <li>{{domxref("DeviceProximityEvent")}}</li> + <li>{{domxref("DOMTransactionEvent")}}</li> + <li>{{domxref("DragEvent")}}</li> + <li>{{domxref("EditingBeforeInputEvent")}}</li> + <li>{{domxref("ErrorEvent")}}</li> + <li>{{domxref("FetchEvent")}}</li> + <li>{{domxref("FocusEvent")}}</li> + <li>{{domxref("GamepadEvent")}}</li> + <li>{{domxref("HashChangeEvent")}}</li> + <li>{{domxref("IDBVersionChangeEvent")}}</li> + <li>{{domxref("InputEvent")}}</li> + <li>{{domxref("KeyboardEvent")}}</li> + <li>{{domxref("MediaStreamEvent")}}</li> + <li>{{domxref("MessageEvent")}}</li> + <li>{{domxref("MouseEvent")}}</li> + <li>{{domxref("MutationEvent")}}</li> + <li>{{domxref("OfflineAudioCompletionEvent")}}</li> + <li>{{domxref("PageTransitionEvent")}}</li> + <li>{{domxref("PointerEvent")}}</li> + <li>{{domxref("PopStateEvent")}}</li> + <li>{{domxref("ProgressEvent")}}</li> + <li>{{domxref("RelatedEvent")}}</li> + <li>{{domxref("RTCDataChannelEvent")}}</li> + <li>{{domxref("RTCIdentityErrorEvent")}}</li> + <li>{{domxref("RTCIdentityEvent")}}</li> + <li>{{domxref("RTCPeerConnectionIceEvent")}}</li> + <li>{{domxref("SensorEvent")}}</li> + <li>{{domxref("StorageEvent")}}</li> + <li>{{domxref("SVGEvent")}}</li> + <li>{{domxref("SVGZoomEvent")}}</li> + <li>{{domxref("TimeEvent")}}</li> + <li>{{domxref("TouchEvent")}}</li> + <li>{{domxref("TrackEvent")}}</li> + <li>{{domxref("TransitionEvent")}}</li> + <li>{{domxref("UIEvent")}}</li> + <li>{{domxref("UserProximityEvent")}}</li> + <li>{{domxref("WebGLContextEvent")}}</li> + <li>{{domxref("WheelEvent")}}</li> +</ul> +</div> + +<h2 id="Properties" name="Properties">Konstruktor</h2> + +<dl> + <dt>{{domxref("Event.Event", "Event()")}}</dt> + <dd>Membuat sebuah object <code>Event</code></dd> +</dl> + +<h2 id="Properties" name="Properties">Properti</h2> + +<p><em>Antarmuka ini tidak mewarisi properti manapun.</em></p> + +<dl> + <dt>{{domxref("Event.bubbles")}} {{readonlyinline}}</dt> + <dd>Sebuah boolean yang menunjukan apakah event bubbles melalui DOM atau tidak.</dd> + <dt>{{domxref("Event.cancelBubble")}} {{non-standard_inline}}</dt> + <dd>Alternatif non-standar untuk {{domxref("Event.stopPropagation()")}}.</dd> + <dt>{{domxref("Event.cancelable")}} {{readonlyinline}}</dt> + <dd>Sebuah boolean yang menunjukan apakah event bisa dibatalkan.</dd> + <dt>{{domxref("Event.currentTarget")}} {{readonlyinline}}</dt> + <dd>Sebuah referensi untuk target terdaftar saat ini untuk event.</dd> + <dt>{{domxref("Event.defaultPrevented")}} {{readonlyinline}}</dt> + <dd>Menunjukan apakah {{domxref("event.preventDefault()")}} telah dipanggil pada event atau belum.</dd> + <dt>{{domxref("Event.eventPhase")}} {{readonlyinline}}</dt> + <dd>Menunjukan fase aliran event yang sedang diproses.</dd> + <dt>{{domxref("Event.explicitOriginalTarget")}} {{non-standard_inline}} {{readonlyinline}}</dt> + <dd>Eksplisit target dari event (Mozilla-specific).</dd> + <dt>{{domxref("Event.originalTarget")}} {{non-standard_inline}} {{readonlyinline}}</dt> + <dd>Target dari event, sebelum penargetan ulang lain (Mozilla-specific).</dd> + <dt>{{domxref("Event.returnValue")}} {{non-standard_inline}}</dt> + <dd>Alternatif nonstandard untuk {{domxref("Event.preventDefault()")}} dan {{domxref("Event.defaultPrevented")}}. (spesifik Internet Explorer lama)</dd> + <dt>{{domxref("Event.srcElement")}} {{non-standard_inline}}</dt> + <dd>Alias nonstandard untuk {{domxref("Event.target")}}. (spesifik Internet Explorer lama)</dd> + <dt>{{domxref("Event.target")}} {{readonlyinline}}</dt> + <dd>Sebuah referensi untuk target dimana event pertama kali dikirimkan.</dd> + <dt>{{domxref("Event.timeStamp")}} {{readonlyinline}}</dt> + <dd>Waktu ketika event dibuat.</dd> + <dt>{{domxref("Event.type")}} {{readonlyinline}}</dt> + <dd>Nama dari event (case-insensitive).</dd> + <dt>{{domxref("Event.isTrusted")}} {{readonlyinline}}</dt> + <dd>Menunjukan apakah event di terima browser atau tidak (mis. ketika user klik) atau dengan sebuah script (menggunakan sebuah method event buatan, seperti <a href="/en-US/docs/DOM/event.initEvent">event.initEvent</a>)</dd> +</dl> + +<h2 id="Methods" name="Methods">Method</h2> + +<p><em>Antarmuka ini tidak mewarisi method manapun.</em></p> + +<dl> + <dt>{{domxref("Event.initEvent()")}} {{deprecated_inline}}</dt> + <dd>Menginisialisasi nilai dari Event yang dibuat. Jika event telah dikirimkan, method ini tidak akan digunakan.</dd> + <dt>{{domxref("Event.preventBubble()")}} {{non-standard_inline}} {{Obsolete_inline(24)}}</dt> + <dd>Mencegah event agar tidak menggelegak. Usang, gunakan {{domxref("event.stopPropagation")}} sebagai gantinya.</dd> + <dt>{{domxref("Event.preventCapture()")}} {{non-standard_inline}} {{Obsolete_inline(24)}}</dt> + <dd>Usang, gunakan {{domxref("event.stopPropagation")}} sebagai gantinya.</dd> + <dt>{{domxref("Event.preventDefault()")}}</dt> + <dd>Membatalkan event event (jika cancelable).</dd> + <dt>{{domxref("Event.stopImmediatePropagation()")}}</dt> + <dd>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)</dd> + <dt>{{domxref("Event.stopPropagation()")}}</dt> + <dd>Menghentikan penyebaran events lebih jauh pada DOM.</dd> + <dt>{{domxref("Event.getPreventDefault()")}} {{non-standard_inline}}</dt> + <dd>Non-standard. Mengembailkan nilai dari {{domxref("Event.defaultPrevented")}}. Gunakan {{domxref("Event.defaultPrevented")}} sebagai gantinya.</dd> +</dl> + +<h2 id="See_also" name="See_also">Lihat Juga</h2> + +<ul> + <li>Jenis event yang tersedia: <a href="/id/docs/Web/Reference/Events">Referensi Event</a></li> + <li><a href="/en-US/docs/Web/API/Event/Comparison_of_Event_Targets">Comparison of Event Targets</a> (target vs currentTarget vs relatedTarget vs originalTarget)</li> + <li><a href="/en-US/docs/Web/Guide/DOM/Events/Creating_and_triggering_events">Creating and triggering custom events</a></li> + <li>For Firefox add-on developers: + <ul> + <li><a href="/en-US/docs/Listening_to_events_in_Firefox_extensions">Listening to events in Firefox extensions</a></li> + <li><a href="/en-US/docs/Listening_to_events_on_all_tabs">Listening to events on all tabs</a></li> + </ul> + </li> +</ul> 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 +--- +<div>{{ApiRef("DOM")}}</div> + +<p>The <code><strong>target</strong></code> 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.</p> + +<h2 id="Syntax">Syntax</h2> + +<pre class="syntaxbox">var <em>theTarget</em> = <em>event</em>.target;</pre> + +<h3 id="Value">Value</h3> + +<p>{{domxref("EventTarget")}}</p> + +<h2 id="Example">Example</h2> + +<p>Properti <code>event.target</code> dapat digunakan untuk mengimplementasikan <strong>event delegation</strong>.</p> + +<pre class="brush: js">// 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); +</pre> + +<h2 id="Spesifikasi">Spesifikasi</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th>Specification</th> + <th>Status</th> + <th>Comment</th> + </tr> + <tr> + <td>{{SpecName("DOM WHATWG", "#dom-event-target", "Event.target")}}</td> + <td>{{Spec2("DOM WHATWG")}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName("DOM4", "#dom-event-target", "Event.target")}}</td> + <td>{{Spec2("DOM4")}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName("DOM2 Events", "#Events-Event-target", "Event.target")}}</td> + <td>{{Spec2("DOM2 Events")}}</td> + <td>Initial definition</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + + + +<p>{{Compat("api.Event.target")}}</p> + +<h3 id="Compatibility_notes">Compatibility notes</h3> + +<p>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 <code>target</code> property, and it has the same semantics as <code>Event.target</code>.</p> + +<pre class="brush: js">function hide(e) { + // Support IE6-8 + var target = e.target || e.srcElement; + target.style.visibility = 'hidden'; +} +</pre> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="/en-US/docs/Web/API/Event/Comparison_of_Event_Targets">Comparison of Event Targets</a></li> +</ul> 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 +--- +<div>{{DefaultAPISidebar("Fetch API")}}</div> + +<p class="summary"><font><font>Fetch Data API menyediakan antarmuka untuk pemanggilan sumber daya data(termasuk di seluruh jaringan). </font><font>Ini akan terasa familiar bagi siapa saja yang telah menggunakan </font></font><span class="seoSummary">{{DOMxRef("XMLHttpRequest")}}</span><font><font>, tetapi untuk API yang terbaru menyediakan serangkaian fitur yang lebih kuat dan fleksibel.</font></font></p> + +<h2 id="Konsep_dan_Penggunaan"><font><font>Konsep dan </font></font><font><font>Penggunaan</font></font></h2> + +<p><font><font>"Fetch" / pengambilan resource data menyediakan definisi umum yaitu objek</font></font>{{DOMxRef("Request")}} dan<font><font> </font></font>{{DOMxRef("Response")}} atau permintaan dan tanggapan<font><font>(dan hal-hal lain yang kaitannya dengan permintaan jaringan/"HTTP"). </font><font>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).</font></font></p> + +<p>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).</p> + +<p><font><font>Untuk membuat permintaan dan mengambil sumber daya data, bisa menggunakan metode </font></font>{{DOMxRef("WindowOrWorkerGlobalScope.fetch()")}} <font><font>ini. Metode </font><font>ini diimplementasikan dalam beberapa antarmuka aplikasi, khususnya pada </font></font>{{DOMxRef("Window")}} <font><font>dan </font></font>{{DOMxRef("WorkerGlobalScope")}}<font><font>. </font><font>Ini membuatnya tersedia dalam hampir semua konteks yang mana anda mungkin menginginkan untuk mengambil sumber data / resource nya.</font></font></p> + +<p><font><font>Metode </font></font><code>fetch()</code><font><font> 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. </font><font>Hal ini mampu untuk mengembalikan hasil/return </font></font>{{DOMxRef("Promise")}} <font><font>yang memutuskan ke </font></font>{{DOMxRef("Response")}} kepada <font><font>permintaan itu sendiri, apakah hal tersebut berhasil atau tidak pada saat terjadi response/tanggapan sumber data. Anda juga bisa secara opsional mengirimkan objek pilihan </font></font><code>init</code><font><font>sebagai argumen keduanya (lihat </font></font>{{DOMxRef("Request")}}<font><font>).</font></font></p> + +<p><font><font>Setelah </font></font>{{DOMxRef("Response")}} telah <font><font>dipanggil, ada sejumlah metode yang tersedia untuk menentukan apa saja konten tubuh(pikirkan pada elemen html) dan bagaimana penanganannya (lihat </font></font>{{DOMxRef("Body")}})<font><font>.</font></font></p> + +<p><font><font>Anda juga bisa membuat permintaan dan response secara langsung menggunakan </font></font>{{DOMxRef("Request.Request", "Request()")}}<font><font>dan konstruktor </font></font>{{DOMxRef("Response.Response", "Response()")}}<font><font>, namun Anda tidak bisa melakukan ini secara langsung. </font><font>Malahan, ini lebih cenderung sebagai hasil dari aksi yang dilakukan oleh API yang lainnya (misalnya, </font></font>{{DOMxRef("FetchEvent.respondWith()")}} <font><font>dari </font></font>service workers (kalo loe yang main teknologinya PWA pasti tau coy)<font><font>).</font></font></p> + +<div class="note"> +<p><strong><font><font>Catatan</font></font></strong><font><font> : Cari tahu lebih lanjut mengenai penggunaan fitur Fetch API di </font></font><a href="https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch"><font><font>cara menggunakan fetch</font></font></a><font><font> , dan pelajari konsepnya di </font></font><a href="https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Basic_concepts"><font><font>konsep dasar fetch </font></font></a><font><font>.</font></font></p> +</div> + +<h3 id="Batalkan_fetch">Batalkan fetch</h3> + +<p><font><font>Web browser sudah mulai menambahkan dukungan eksperimental untuk </font><font>antarmuka </font></font>{{DOMxRef("AbortController")}} <font><font>dan </font></font>{{DOMxRef("AbortSignal")}}<font><font>(alias API Abort), yang memungkinkan operasi seperti Fetch dan XHR untuk dibatalkan apabila mereka belum selesai secara sempurna dipanggil. </font><font>Lihat halaman antarmuka untuk detail lebih lanjut.</font></font></p> + +<p>Browsers have started to add experimental support for the {{DOMxRef("AbortController")}} and {{DOMxRef("AbortSignal")}} interfaces (aka The Abort API), which allow operation</p> + +<p> </p> + +<h2 id="Antarmuka_metode_Fetch"><font><font>Antarmuka metode Fetch</font></font></h2> + +<dl> + <dt><a href="https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch" title="Metode fetch () dari mixin WindowOrWorkerGlobalScope memulai proses pengambilan sumber daya dari jaringan. Ini mengembalikan janji yang diselesaikan ke objek Respons yang mewakili respons terhadap permintaan Anda. Janji tidak menolak kesalahan HTTP - melainkan hanya menolak kesalahan jaringan; maka penangan harus memeriksa kesalahan HTTP."><code>WindowOrWorkerGlobalScope.fetch()</code></a></dt> + <dd><font><font>Metode </font></font><code>fetch()</code><font><font> yang digunakan untuk mengambil sumber data.</font></font></dd> + <dt><a href="https://developer.mozilla.org/en-US/docs/Web/API/Headers" title="Antarmuka Header dari Fetch API memungkinkan Anda untuk melakukan berbagai tindakan pada permintaan HTTP dan header respons. Tindakan ini termasuk mengambil, mengatur, menambah, dan menghapus. Objek Header memiliki daftar header terkait, yang awalnya kosong dan terdiri dari nol atau lebih pasangan nama dan nilai. Anda dapat menambahkan ini menggunakan metode seperti append () (lihat Contoh.) Di semua metode antarmuka ini, nama header dicocokkan dengan urutan byte case-insensitive."><code>Headers</code></a></dt> + <dd><font><font>Merupakan header respons / permintaan, memungkinkan Anda untuk menanyakannya(query) dan mengambil tindakan yang berbeda dimana ini tergantung pada hasilnya.</font></font></dd> + <dt><a href="https://developer.mozilla.org/en-US/docs/Web/API/Request" title="Antarmuka Permintaan API Ambil mewakili permintaan sumber daya."><code>Request</code></a></dt> + <dd><font><font>Merupakan permintaan sumber data.</font></font></dd> + <dt><a href="https://developer.mozilla.org/en-US/docs/Web/API/Response" title="Antarmuka Respons API Ambil mewakili respons terhadap permintaan."><code>Response</code></a></dt> + <dd><font><font>Merupakan respons terhadap permintaan.</font></font></dd> +</dl> + +<h2 id="Fetch_mixin">Fetch mixin</h2> + +<dl> + <dt>{{DOMxRef("Body")}}</dt> + <dd><font><font>Menyediakan metode yang berkaitan dengan konten pada respons / permintaan, memungkinkan Anda untuk menyatakan jenis kontennya dan bagaimana penanganannya.</font></font></dd> +</dl> + +<h2 id="Spesifikasi">Spesifikasi</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Spesifikasi</th> + <th scope="col">Status</th> + <th scope="col">Keterangan</th> + </tr> + <tr> + <td>{{SpecName("Fetch")}}</td> + <td>{{Spec2("Fetch")}}</td> + <td>Definisi awal</td> + </tr> + </tbody> +</table> + +<h2 id="Kompatibilitas_Browser">Kompatibilitas Browser</h2> + + + +<p>{{Compat("api.WindowOrWorkerGlobalScope.fetch")}}</p> + +<h2 id="Lihat_juga_untuk">Lihat juga untuk </h2> + +<ul> + <li><a href="/en-US/docs/Web/API/Fetch_API/Using_Fetch">Penggunaan metode Fetch</a></li> + <li><a href="/en-US/docs/Web/API/ServiceWorker_API">ServiceWorker API</a></li> + <li><a href="/en-US/docs/Web/HTTP/Access_control_CORS">HTTP access control (CORS)</a></li> + <li><a href="/en-US/docs/Web/HTTP">HTTP</a></li> + <li>M<a href="https://github.com/github/fetch">etode Fetch untuk polyfill</a></li> + <li><a href="/en-US/docs/Web/API/Fetch_API/Basic_concepts">Konsep dasar Fetch</a></li> +</ul> 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 +--- +<p>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.</p> + +<div>{{APIListAlpha}}</div> 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 +--- +<p>{{ draft }}</p> +<p>{{ non-standard_header() }}</p> +<p>{{ B2GOnlyHeader2('certified') }}</p> +<h2 id="Summary">Summary</h2> +<p>This API has 2 purposes:</p> +<ul> + <li>Giving access to detailed information about the current states of the mobile connection of the device</li> + <li>Giving access to the specific capacities embedded within the <abbr title="Integrated Circuit Card">ICC</abbr> (the <abbr title="Subscriber Identity Module">SIM</abbr>/<abbr title="Removable User Identity Module">RUIM</abbr> card)</li> +</ul> +<p>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 <abbr title="Integrated Circuit Card">ICC</abbr>), it is restricted to certified applications only.</p> +<p>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.</p> +<h2 id="State_of_mobile_connection">State of mobile connection</h2> +<p>The state of the mobile connection is divided in two: on the one hand the <code>voice</code> connection, on the other hand the <code>data</code> 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.</p> +<p>Those objects give access to all information related to the quality of the network (<a href="/en-US/docs/DOM/MozMobileConnectionInfo.signalStrength" title="/en-US/docs/DOM/MozMobileConnectionInfo.signalStrength">signal strength</a>, <a href="/en-US/docs/DOM/MozMobileConnectionInfo.relSignalStrength" title="/en-US/docs/DOM/MozMobileConnectionInfo.relSignalStrength">quality of the signal</a>, position of the <a href="/en-US/docs/DOM/MozMobileConnectionInfo.cell" title="/en-US/docs/DOM/MozMobileConnectionInfo.cell">network's cells</a>, <a href="/en-US/docs/DOM/MozMobileConnectionInfo.emergencyCallsOnly" title="/en-US/docs/DOM/MozMobileConnectionInfo.emergencyCallsOnly">restricted usage</a>, <a href="/en-US/docs/DOM/MozMobileConnectionInfo.roaming" title="/en-US/docs/DOM/MozMobileConnectionInfo.roaming">roaming</a>, etc.), and related to <a href="/en-US/docs/DOM/MozMobileConnectionInfo.network" title="/en-US/docs/DOM/MozMobileConnectionInfo.network">the carrier operating the network</a>.</p> +<pre class="brush: js">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); +} +</pre> +<h2 id="ICC_Functionalities">ICC Functionalities</h2> +<p>The functionalities available for the <abbr title="Integrated Circuit Card">ICC</abbr> can be divided into two categories: the management of the <abbr title="Integrated Circuit Card">ICC</abbr> itself and the use of the integrated command available within the <a href="http://en.wikipedia.org/wiki/SIM_Application_Toolkit" title="http://en.wikipedia.org/wiki/SIM_Application_Toolkit">STK</a> (<em>SIM Application Toolkit</em>).</p> +<h3 id="Basic_actions">Basic actions</h3> +<p>The {{domxref("MozMobileConnection")}} provides a set of methods to deal with common behaviors on <abbr title="Integrated Circuit Card">ICC</abbr>s.</p> +<div class="note"> + <p><strong>Note:</strong> All original methods from the <code>MozMobileConnection</code> interface are fully asynchronous. They all return a {{domxref("DOMRequest")}} object which has an <code>onsuccess</code> and <code>onerror</code> event handler to handle the success or failure of the method call.</p> +</div> +<h4 id="Card_lock">Card lock</h4> +<p>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.</p> +<p>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.</p> +<div class="note"> + <p><strong>Note:</strong> 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:</p> + <ul> + <li>The {{event("icccardlockerror")}} event is triggered each time a call to {{domxref("MozMobileConnection.setCardLock","setCardLock()")}} or {{domxref("MozMobileConnection.unlockCardLock","unlockCardLock()")}} fails.</li> + <li>The {{event("cardstatechange")}} event is triggered each time the {{domxref("MozMobileConnection.cardState","cardState")}} property changes.</li> + </ul> +</div> +<pre class="brush: js">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(); +} +</pre> +<h4 id="MMI_Messages">MMI Messages</h4> +<p><abbr title="Man Machine Interface">MMI</abbr> messages are human understandable code that, once typed with a phone keyboard, allow to trigger specific action from the <a class="external" href="http://en.wikipedia.org/wiki/Radio_Interface_Layer" title="Wikipedia: Radio Interface Layer">RIL</a> or get response from the network through a <a class="external" href="http://en.wikipedia.org/wiki/USSD" title="Wikipedia: Unstructured Supplementary Service Data">USSD</a> request. A common example is typing a short code to get the <a href="http://en.wikipedia.org/wiki/International_Mobile_Station_Equipment_Identity" title="http://en.wikipedia.org/wiki/International_Mobile_Station_Equipment_Identity">IMEI</a> phone number.</p> +<p>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:</p> +<ul> + <li>If the <abbr title="Man Machine Interface">MMI</abbr> code requires sending a <abbr title="Unstructured Supplementary Service Data">USSD</abbr> request, the request's <code>success</code> means that the <abbr title="Radio Interface Layer">RIL</abbr> has successfully processed and sent the <abbr title="Unstructured Supplementary Service Data">USSD</abbr> request to the network. However, the network reply is reported through the {{event("ussdreceived")}} event.</li> + <li>If the <abbr title="Man Machine Interface">MMI</abbr> code is not associated with a <abbr title="Unstructured Supplementary Service Data">USSD</abbr> but with another <abbr title="Radio Interface Layer">RIL</abbr> request, its result, if one is needed, is sent via the returned request's <code>success</code> or <code>error</code>.</li> +</ul> +<pre class="brush: js">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."); +} +</pre> +<h4 id="Call_forwarding_options">Call forwarding options</h4> +<p>Call forwarding options allow to define how a call can or cannot be forwarded to another phone number.</p> +<p>Those options are handled with the {{domxref("MozMobileConnection.getCallForwardingOption","getCallForwardingOption()")}} and {{domxref("MozMobileConnection.setCallForwardingOption","setCallForwardingOption()")}} methods.</p> +<pre class="brush: js">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); +} +</pre> +<h3 id="STK_commands">STK commands</h3> +<p>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.</p> +<div class="warning"> + <p><strong>Warning:</strong> 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.</p> +</div> +<h2 id="Specification">Specification</h2> +<p>Not part of any specification.</p> +<h2 id="See_also">See also</h2> +<ul> + <li>{{domxref("window.navigator.mozMobileConnection","navigator.mozMobileConnection")}}</li> + <li>{{domxref("MozMobileConnection")}}</li> + <li>{{domxref("MozMobileConnectionInfo")}}</li> + <li>{{domxref("MozMobileICCInfo")}}</li> + <li>{{domxref("MozMobileNetworkInfo")}}</li> + <li>{{domxref("MozMobileCFInfo")}}</li> + <li>{{domxref("MozMobileCellInfo")}}</li> + <li>{{domxref("MozIccManager")}}</li> + <li>{{domxref("MozStkCommandEvent")}}</li> +</ul> 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 +--- +<p>{{ apiref() }}</p> + +<p>Antarmuka <code><strong>Navigator</strong></code> mewakili negara dan identitas pengguna. Memungkinkan script untuk melakukan query dan mendaftarkan diri untuk melakukan suatu aktivitas.</p> + +<p>Objek <code>Navigator</code> dapat dipanggil menggunakan properti {{domxref("Window.navigator")}}.</p> + +<h2 id="Properti">Properti</h2> + +<p><em>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")}}.</em></p> + +<h3 id="Standard">Standard</h3> + +<dl> + <dt>{{domxref("Navigator.activeVRDisplays")}} {{readonlyInline}}{{experimental_inline}}</dt> + <dd>Mengembalikan sebuah array yang berisi setiap objek {{domxref("VRDisplay")}} yang menyajikan ({{domxref("VRDisplay.ispresenting")}} adalah <code>true</code>).</dd> + <dt>{{domxref("NavigatorID.appCodeName")}} {{readonlyInline}}{{experimental_inline}}</dt> + <dd>Mengembalikan internal nama "code" browser. Jangan mengandalkan properti ini untuk mengembalikan nilai yang benar.</dd> + <dt>{{domxref("NavigatorID.appName")}} {{readonlyInline}}{{experimental_inline}}</dt> + <dd>Mengembalikan {{domxref("DOMString")}} dengan nama official dari browser. Jangan mengandalkan properti ini untuk mengembalikan nilai yang benar.</dd> + <dt>{{domxref("NavigatorID.appVersion")}} {{readonlyInline}}{{experimental_inline}}</dt> + <dd>Mengembalikan versi browser sebagai {{domxref("DOMString")}}. Jangan mengandalkan properti ini untuk mengembalikan nilai yang benar.</dd> + <dt>{{domxref("Navigator.battery")}} {{readonlyInline}}</dt> + <dd>Mengembalikan objek {{domxref("BatteryManager")}} yang memberikan informasi tentang status isi baterai.</dd> + <dt>{{domxref("Navigator.connection")}} {{readonlyInline}}{{experimental_inline}}</dt> + <dd>Menyediakan sebuah objek {{domxref("NetworkInformation")}} yang berisi informasi tentang koneksi jaringan pada perangkat.</dd> + <dt>{{domxref("Navigator.geolocation")}} {{readonlyInline}}</dt> + <dd>Mengembalikan objek {{domxref("Geolocation")}} yang memungkinkan untuk mengakses lokasi perangkat.</dd> + <dt>{{domxref("NavigatorConcurrentHardware.hardwareConcurrency")}} {{readOnlyInline}}</dt> + <dd>Mengembalikan jumlah inti logical processor yag tersedia.</dd> + <dt>{{domxref("NavigatorPlugins.javaEnabled")}} {{readonlyInline}}{{experimental_inline}}</dt> + <dd>Returns a {{domxref("Boolean")}} flag indicating whether the host browser is Java-enabled or not.</dd> + <dt>{{domxref("NavigatorLanguage.language")}} {{readonlyInline}}</dt> + <dd>Mengembalikan {{domxref("DOMString")}} berdasarkan bahasa yang digunakan, biasanya bahasa UI pada browser. Nilai <code>null</code> akan dikembalikan jika tidak diketahui.</dd> + <dt>{{domxref("NavigatorLanguage.languages")}} {{readonlyInline}}</dt> + <dd>Mengembalikan sebuah array dari {{domxref("DOMString")}} berdasarkan bahasa yang diketahui pengguna, berdasarkan pengaturan.</dd> + <dt>{{domxref("NavigatorPlugins.mimeTypes")}} {{readonlyInline}}{{experimental_inline}}</dt> + <dd>Mengembalikan daftar {{domxref("MimeTypeArray")}} dari tipe MIME yang didukung oleh browser.</dd> + <dt>{{domxref("NavigatorOnLine.onLine")}} {{readonlyInline}}</dt> + <dd>Mengembalikan sebuah {{domxref("Boolean")}} yang menunjukan apakah browser dalam keadaan online.</dd> + <dt>{{domxref("Navigator.oscpu")}}</dt> + <dd>Mengembalikan sebuah string berdasarkan sistem operasi.</dd> + <dt>{{domxref("Navigator.permissions")}} {{readonlyinline}}{{experimental_inline}}</dt> + <dd>Mengembalikan objek {{domxref("Permissions")}} yang dapat digunakan untuk query dan membaharui status izin dari APIs yang di cakup di <a href="/en-US/docs/Web/API/Permissions_API">Permissions API</a>.</dd> + <dt>{{domxref("NavigatorID.platform")}} {{readonlyInline}}{{experimental_inline}}</dt> + <dd>Returns a string representing the platform of the browser. Do not rely on this function to return a significant value.</dd> + <dt>{{domxref("NavigatorPlugins.plugins")}} {{readonlyInline}}{{experimental_inline}}</dt> + <dd>Returns a {{domxref("PluginArray")}} listing the plugins installed in the browser.</dd> + <dt>{{domxref("NavigatorID.product")}} {{readonlyInline}} {{experimental_inline}}</dt> + <dd>Always returns <code>'Gecko'</code>, on any browser. This property is kept only for compatibility purpose.</dd> + <dt>{{domxref("NavigatorID.userAgent")}} {{readonlyInline}}</dt> + <dd>Returns the user agent string for the current browser.</dd> + <dt>{{domxref("Navigator.serviceWorker")}} {{readonlyInline}}</dt> + <dd>Returns a {{domxref("ServiceWorkerContainer")}} object, which provides access to registration, removal, upgrade, and communication with the {{domxref("ServiceWorker")}} objects for the <a href="https://html.spec.whatwg.org/multipage/browsers.html#concept-document-window">associated document</a>.</dd> +</dl> + +<h3 id="Methods" name="Methods">Non-standard</h3> + +<div class="note"> +<p>Firefox OS devices adds more non-standard properties. You can consult them on the <a href="/en-US/docs/Mozilla/Firefox_OS/API/Navigator">Firefox OS Navigator extensions article</a>.</p> +</div> + +<p>{{domxref("Navigator.buildID")}} {{non-standard_inline}}</p> + +<dl> + <dd>Returns the build identifier of the browser (e.g., "2006090803").</dd> + <dt>{{domxref("Navigator.cookieEnabled")}} {{non-standard_inline}}</dt> + <dd>Returns a boolean indicating whether cookies are enabled in the browser or not.</dd> + <dt>{{domxref("Navigator.credentials")}} {{non-standard_inline}}</dt> + <dd>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. </dd> + <dt>{{domxref("Navigator.doNotTrack")}} {{non-standard_inline}}</dt> + <dd>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.</dd> + <dt>{{domxref("Navigator.id")}} {{non-standard_inline}}</dt> + <dd>Returns the {{domxref("window.navigator.id", "id")}} object which you can use to add support for <a href="/en-US/docs/BrowserID" title="BrowserID">BrowserID</a> to your web site.</dd> + <dt>{{domxref("Navigator.mediaDevices")}} {{non-standard_inline}}</dt> + <dd>Returns a reference to the {{domxref("MediaDevices")}} interface.</dd> + <dt>{{domxref("Navigator.mozNotification")}} {{deprecated_inline("22")}} {{non-standard_inline}}<br> + {{domxref("Navigator.webkitNotification")}}</dt> + <dd>Returns a {{domxref("navigator.mozNotification", "notification")}} object you can use to deliver notifications to the user from your web application.</dd> + <dt>{{domxref("Navigator.mozSocial")}} {{non-standard_inline}}</dt> + <dd>The Object, returned by the <code>navigator.mozSocial</code> property, is available within the social media provider's panel to provide functionality it may need.</dd> + <dt>{{domxref("Navigator.presentation")}} {{non-standard_inline}}</dt> + <dd>Returns a reference to the {{domxref("Presentation")}} API.</dd> + <dt>{{domxref("Navigator.productSub")}} {{non-standard_inline}}</dt> + <dd>Returns the build number of the current browser (e.g., "20060909").</dd> + <dt>{{domxref("Navigator.securitypolicy")}} {{non-standard_inline}}</dt> + <dd>Returns an empty string. In Netscape 4.7x, returns "US & CA domestic policy" or "Export policy".</dd> + <dt>{{domxref("Navigator.standalone")}} {{non-standard_inline}}</dt> + <dd>Returns a boolean indicating whether the browser is running in standalone mode. Available on Apple's iOS Safari only.</dd> + <dt>{{domxref("Navigator.vendor")}} {{non-standard_inline}}</dt> + <dd>Returns the vendor name of the current browser (e.g., "Netscape6").</dd> + <dt>{{domxref("Navigator.vendorSub")}} {{non-standard_inline}}</dt> + <dd>Returns the vendor version number (e.g. "6.1").</dd> + <dt>{{domxref("Navigator.webkitPointer")}} {{non-standard_inline}}</dt> + <dd>Returns a PointerLock object for the <a href="/en-US/docs/API/Pointer_Lock_API" title="Mouse Lock API">Mouse Lock API</a>.</dd> +</dl> + +<h2 id="Methods" name="Methods">Methods</h2> + +<p><em>Doesn't inherit any method, but implements those defined in {{domxref("NavigatorID")}}, {{domxref("NavigatorContentUtils")}}, <em>{{domxref("NavigatorUserMedia")}}, </em>and {{domxref("NavigatorStorageUtils")}}.</em></p> + +<h3 id="Standard_2">Standard</h3> + +<dl> + <dt>{{domxref("Navigator.getVRDisplays()")}} {{experimental_inline}}</dt> + <dd>Returns a promise that resolves to an array of {{domxref("VRDisplay")}} objects representing any available VR devices connected to the computer.</dd> + <dt>{{domxref("Navigator.getUserMedia", "NavigatorUserMedia.getUserMedia()")}}</dt> + <dd>After having prompted the user for permission, returns the audio or video stream associated to a camera or microphone on the local computer.</dd> + <dt>{{domxref("Navigator.registerContentHandler()")}}</dt> + <dd>Allows web sites to register themselves as a possible handler for a given MIME type.</dd> + <dt>{{domxref("Navigator.registerProtocolHandler()")}}</dt> + <dd>Allows web sites to register themselves as a possible handler for a given protocol.</dd> + <dt>{{domxref("Navigator.requestMediaKeySystemAccess()")}} {{experimental_inline}}</dt> + <dd>Returns a <span style="line-height: 19.0909080505371px;">{{jsxref("Promise")}} for a MediaKeySystemAccess object.</span></dd> + <dt>{{domxref("Navigator.sendBeacon()")}}{{experimental_inline}}</dt> + <dd>Used to asynchronously transfer small HTTP data from the User Agent to a web server.</dd> + <dt>{{domxref("NavigatorID.taintEnabled()")}} {{deprecated_inline("1.7.8")}} {{obsolete_inline("9.0")}} {{experimental_inline}}</dt> + <dd>Returns <code>false</code>. JavaScript taint/untaint functions removed in JavaScript 1.2.</dd> + <dt>{{domxref("Navigator.vibrate()")}} {{gecko_minversion_inline("11.0")}}</dt> + <dd>Causes vibration on devices with support for it. Does nothing if vibration support isn't available.</dd> +</dl> + +<h3 id="Specification" name="Specification">Non-standard</h3> + +<div class="note"> +<p>Firefox OS devices adds more non-standard methods. You can consult them on the <a href="/en-US/docs/Mozilla/Firefox_OS/API/Navigator">Firefox OS Navigator extensions article</a>.</p> +</div> + +<p>{{domxref("Navigator.mozIsLocallyAvailable()")}} {{non-standard_inline}}</p> + +<dl> + <dd>Lets code check to see if the document at a given URI is available without using the network.</dd> + <dt>{{domxref("Navigator.mozPay()")}} {{non-standard_inline}}</dt> + <dd>Allows in-app payment.</dd> +</dl> 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 +--- +<div>{{APIRef("Media Capture and Streams")}}</div> + +<p>The <strong><code>Navigator.mediaDevices</code></strong> 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.</p> + +<h2 id="Syntax">Syntax</h2> + +<pre class="syntaxbox notranslate">var <em>mediaDevices</em> = navigator.mediaDevices; +</pre> + +<h3 id="Return_value">Return value</h3> + +<p>The {{domxref("MediaDevices")}} singleton object. Usually, you just use this object's members directly, such as by calling {{domxref("navigator.mediaDevices.getUserMedia()")}}.</p> + +<h2 id="Spesifikasi">Spesifikasi</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Spesifikasi</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('Media Capture', '#mediadevices', 'NavigatorUserMedia.mediaDevices')}}</td> + <td>{{Spec2('Media Capture')}}</td> + <td>Initial definition.</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + + + +<p>{{Compat("api.Navigator.mediaDevices")}}</p> + +<h2 id="Lihat_juga">Lihat juga</h2> + +<ul> + <li><a href="/en-US/docs/Web/API/Media_Streams_API">Media Capture and Streams API</a>: The entry point to the documentation about the entire media stream API.</li> + <li><a href="/en-US/docs/Web/API/WebRTC_API">WebRTC API</a>: Documentation about the WebRTC API, which is closely related.</li> +</ul> 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 +--- +<p>{{APIRef("Service Workers API")}}</p> + +<p><code><strong>Navigator.serviceWorker</strong></code> adalah properti yang hanya bisa dibaca, mengembalikan objek {{domxref("ServiceWorkerContainer")}} untuk <a href="https://html.spec.whatwg.org/multipage/browsers.html#concept-document-window">dokumen terkait</a>, yang memberikan akses untuk registrasi, penghapusan, upgrade, dan berkomunikasi dengan {{domxref("ServiceWorker")}}.</p> + +<h2 id="Sintaks">Sintaks</h2> + +<pre class="syntaxbox">var workerContainerInstance = navigator.serviceWorker; +</pre> + +<h3 id="Nilai">Nilai</h3> + +<p>{{domxref("ServiceWorkerContainer")}}.</p> + +<h2 id="Spesifikasi">Spesifikasi</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Spesifikasi</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('Service Workers', '#navigator-service-worker', 'navigator.serviceWorker')}}</td> + <td>{{Spec2('Service Workers')}}</td> + <td>Initial definition.</td> + </tr> + </tbody> +</table> + +<h2 id="Kompabilitas_Browser">Kompabilitas Browser</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Fitur</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari (WebKit)</th> + </tr> + <tr> + <td>Dukungan dasar</td> + <td>{{CompatChrome(40.0)}}</td> + <td>{{ CompatGeckoDesktop("44.0") }}<sup>[1]</sup></td> + <td>{{CompatNo}}</td> + <td>24</td> + <td>{{CompatNo}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Fitur</th> + <th>Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>Firefox OS</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + <th>Chrome for Android</th> + </tr> + <tr> + <td>Dukungan dasar</td> + <td>{{CompatUnknown}}</td> + <td>{{ CompatGeckoMobile("44.0") }}</td> + <td>{{ CompatVersionUnknown }}</td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<p>[1] Service workers (dan <a href="/en-US/docs/Web/API/Push_API">Push</a>) telah di non-aktifkan di <a href="https://www.mozilla.org/en-US/firefox/organizations/">Firefox 45 Extended Support Release</a> (ESR.)</p> + +<h2 id="Lihat_Juga">Lihat Juga</h2> + +<ul> + <li><a href="/en-US/docs/Web/API/ServiceWorker_API">ServiceWorker API</a></li> + <li><a href="/en-US/docs/Web/API/ServiceWorker_API/Using_Service_Workers">Using Service Workers</a></li> +</ul> 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 +--- +<div> +<p>{{ServiceWorkerSidebar}}</p> + +<p>{{ SeeCompatTable() }}</p> + +<p class="summary">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.</p> +</div> + +<h2 id="Service_worker_concepts_and_usage">Service worker concepts and usage</h2> + +<p>A service worker is an event-driven <a href="https://developer.mozilla.org/en-US/docs/Web/API/Worker">worker</a> 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.)</p> + +<p>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 <a href="/en-US/docs/Web/API/XMLHttpRequest">XHR</a> and <a href="https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Storage">localStorage</a> can't be used inside a service worker.</p> + +<p>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.</p> + +<div class="note"> +<p><strong>Note</strong>: Service Workers win over previous attempts in this area such as <a href="http://alistapart.com/article/application-cache-is-a-douchebag">AppCache</a> 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.</p> +</div> + +<div class="note"> +<p><strong>Note</strong>: Service workers make heavy use of <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise">promises</a>, 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.</p> +</div> + +<h3 id="Registration">Registration</h3> + +<p>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.</p> + +<h3 id="Download_install_and_activate">Download, install and activate</h3> + +<p>At this point, your service worker will observe the following lifecycle:</p> + +<ol> + <li>Download</li> + <li>Install</li> + <li>Activate</li> +</ol> + +<p>The service worker is immediately downloaded when a user first accesses a service worker–controlled site/page.</p> + +<p>After that it is downloaded every 24 hours or so. It *may* be downloaded more frequently, but it <strong>must</strong> be downloaded every 24h to prevent bad scripts from being annoying for too long.</p> + +<p>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.</p> + +<p>If this is the first time a service worker has been made available, installation is attempted, then after a successful installation it is activated.</p> + +<p>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 <em>worker in waiting</em>. 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 <em>active worker</em>).</p> + +<p>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.</p> + +<p>There is also an <code>activate</code> 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.</p> + +<p>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.</p> + +<div class="note"> +<p><strong>Note</strong>: Because <code>oninstall</code>/<code>onactivate</code> could take a while to complete, the service worker spec provides a <code>waitUntil</code> method that, when called <code>oninstall</code> or <code>onactivate</code>, passes a promise. Functional events are not dispatched to the service worker until the promise successfully resolves.</p> +</div> + +<p>For a complete tutorial to show how to build up your first basic example, read <a href="/en-US/docs/Web/API/ServiceWorker_API/Using_Service_Workers">Using Service Workers</a>.</p> + +<h2 id="Other_use_case_ideas">Other use case ideas</h2> + +<p>Service workers are also intended to be used for such things as:</p> + +<ul> + <li>Background data synchronization</li> + <li>Responding to resource requests from other origins</li> + <li>Receiving centralized updates to expensive-to-calculate data such as geolocation or gyroscope, so multiple pages can make use of one set of data</li> + <li>Client-side compiling and dependency management of CoffeeScript, less, CJS/AMD modules, etc. for dev purposes</li> + <li>Hooks for background services</li> + <li>Custom templating based on certain URL patterns</li> + <li>Performance enhancements, for example pre-fetching resources that the user is likely to need in the near future, such as the next few pictures in a photo album.</li> +</ul> + +<p>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:</p> + +<ul> + <li><a href="https://github.com/slightlyoff/BackgroundSync">Background synchronization</a>: Start up a service worker even when no users are at the site, so caches can be updated, etc.</li> + <li><a href="/en-US/docs/Web/API/Push_API">Reacting to push messages</a>: Start up a service worker to send users a message to tell them new content is available.</li> + <li>Reacting to a particular time & date</li> + <li>Entering a geo-fence</li> +</ul> + +<h2 id="Interfaces">Interfaces</h2> + +<dl> + <dt>{{domxref("Cache") }}</dt> + <dd>Represents the storage for {{domxref("Request")}} / {{domxref("Response")}} object pairs that are cached as part of the {{domxref("ServiceWorker")}} life cycle.</dd> + <dt>{{domxref("CacheStorage") }}</dt> + <dd>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.</dd> + <dt>{{domxref("Client") }}</dt> + <dd>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.</dd> + <dt>{{domxref("Clients") }}</dt> + <dd>Represents a container for a list of {{domxref("Client")}} objects; the main way to access the active service worker clients at the current origin.</dd> + <dt>{{domxref("ExtendableEvent") }}</dt> + <dd>Extends the lifetime of the <code>install</code> and <code>activate</code> 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.</dd> + <dt>{{domxref("ExtendableMessageEvent") }}</dt> + <dd>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.</dd> + <dt>{{domxref("FetchEvent") }}</dt> + <dd>The parameter passed into the {{domxref("ServiceWorkerGlobalScope.onfetch")}} handler, <code>FetchEvent</code> 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.</dd> + <dt>{{domxref("InstallEvent") }}</dt> + <dd>The parameter passed into the {{domxref("ServiceWorkerGlobalScope.oninstall", "oninstall")}} handler, the <code>InstallEvent</code> 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. </dd> + <dt>{{domxref("Navigator.serviceWorker") }}</dt> + <dd>Returns a {{domxref("ServiceWorkerContainer")}} object, which provides access to registration, removal, upgrade, and communication with the {{domxref("ServiceWorker")}} objects for the <a href="https://html.spec.whatwg.org/multipage/browsers.html#concept-document-window">associated document</a>.</dd> + <dt>{{domxref("NotificationEvent") }}</dt> + <dd>The parameter passed into the {{domxref("ServiceWorkerGlobalScope.onnotificationclick", "onnotificationclick")}} handler, the <code>NotificationEvent</code> interface represents a notification click event that is dispatched on the {{domxref("ServiceWorkerGlobalScope")}} of a {{domxref("ServiceWorker")}}.</dd> + <dt>{{domxref("ServiceWorker") }}</dt> + <dd>Represents a service worker. Multiple browsing contexts (e.g. pages, workers, etc.) can be associated with the same <code>ServiceWorker</code> object.</dd> + <dt>{{domxref("ServiceWorkerContainer") }}</dt> + <dd>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.</dd> + <dt>{{domxref("ServiceWorkerGlobalScope") }}</dt> + <dd>Represents the global execution context of a service worker.</dd> + <dt>{{domxref("ServiceWorkerMessageEvent")}}</dt> + <dd>Contains information about an event sent to a {{domxref("ServiceWorkerContainer")}} target. </dd> + <dt>{{domxref("ServiceWorkerRegistration") }}</dt> + <dd>Represents a service worker registration.</dd> + <dt>{{domxref("SyncEvent")}} {{non-standard_inline}}</dt> + <dd> + <p>The SyncEvent interface represents a sync action that is dispatched on the {{domxref("ServiceWorkerGlobalScope")}} of a ServiceWorker. </p> + </dd> + <dt>{{domxref("SyncManager")}} {{non-standard_inline}}</dt> + <dd>Provides an interface for registering and listing sync registrations.</dd> + <dt>{{domxref("WindowClient") }}</dt> + <dd>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.</dd> +</dl> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('Service Workers')}}</td> + <td>{{Spec2('Service Workers')}}</td> + <td>Initial definition.</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<div>{{ CompatibilityTable() }}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari (WebKit)</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatChrome(40.0)}}</td> + <td>{{ CompatGeckoDesktop("44.0") }}<sup>[1]</sup></td> + <td>{{ CompatNo() }}</td> + <td>24</td> + <td>{{ CompatNo() }}</td> + </tr> + <tr> + <td>install/activate events</td> + <td>{{ CompatChrome(40.0) }}</td> + <td>{{ CompatGeckoDesktop("44.0") }}<sup>[1]</sup></td> + <td>{{ CompatNo() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatNo() }}</td> + </tr> + <tr> + <td>fetch event/request/<br> + <code>respondWith()</code></td> + <td>{{CompatChrome(40.0)}}</td> + <td>{{ CompatGeckoDesktop("44.0") }}<sup>[1]</sup></td> + <td>{{ CompatNo() }}</td> + <td>{{ CompatNo() }}</td> + <td>{{ CompatNo() }}</td> + </tr> + <tr> + <td>caches/cache</td> + <td> + <p class="p1">{{CompatChrome(42.0)}}</p> + </td> + <td>{{ CompatGeckoDesktop("39.0") }}<sup>[1]</sup></td> + <td>{{ CompatNo() }}</td> + <td>{{ CompatNo() }}</td> + <td>{{ CompatNo() }}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>Firefox OS</th> + <th>IE Phone</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td> </td> + <td>{{CompatChrome(40.0)}}</td> + <td>{{ CompatGeckoMobile("44.0") }}</td> + <td>{{ CompatVersionUnknown }}</td> + <td>{{ CompatNo() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatNo() }}</td> + </tr> + <tr> + <td> install/activate events</td> + <td>{{ CompatNo() }}</td> + <td>{{CompatChrome(40.0)}}</td> + <td>{{ CompatGeckoMobile("44.0") }}</td> + <td>{{ CompatVersionUnknown }}</td> + <td>{{ CompatNo() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatNo() }}</td> + </tr> + <tr> + <td>fetch event/request/<br> + <code>respondWith()</code></td> + <td>{{ CompatNo() }}</td> + <td>{{CompatChrome(40.0)}}</td> + <td>{{ CompatGeckoMobile("44.0") }}</td> + <td>{{ CompatVersionUnknown }}</td> + <td>{{ CompatNo() }}</td> + <td>{{ CompatNo() }}</td> + <td>{{ CompatNo() }}</td> + </tr> + <tr> + <td>caches/cache</td> + <td>{{ CompatNo() }}</td> + <td>{{CompatChrome(40.0)}}</td> + <td>{{ CompatGeckoMobile("39.0") }}</td> + <td>{{ CompatVersionUnknown }}</td> + <td>{{ CompatNo() }}</td> + <td>{{ CompatNo() }}</td> + <td>{{ CompatNo() }}</td> + </tr> + </tbody> +</table> +</div> + +<p>[1] Service workers (and <a href="/en-US/docs/Web/API/Push_API">Push</a>) have been disabled in the <a href="https://www.mozilla.org/en-US/firefox/organizations/">Firefox 45 Extended Support Release</a> (ESR.)</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="https://serviceworke.rs">ServiceWorker Cookbook</a></li> + <li><a href="/en-US/docs/Web/API/ServiceWorker_API/Using_Service_Workers">Using Service Workers</a></li> + <li><a href="https://github.com/mdn/sw-test">Service workers basic code example</a></li> + <li><a href="https://jakearchibald.github.io/isserviceworkerready/">Is ServiceWorker ready?</a></li> + <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise">Promises</a></li> + <li><a href="/en-US/docs/Web/Guide/Performance/Using_web_workers">Using web workers</a></li> + <li><a href="https://www.fastly.com/blog/best-practices-for-using-the-vary-header">Best Practices for using the VARY header</a></li> +</ul> 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 +--- +<p>{{ServiceWorkerSidebar}}</p> + +<p>{{ SeeCompatTable() }}</p> + +<div class="summary"> +<p>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. </p> +</div> + +<h2 id="Premis_Service_Workers">Premis Service Workers</h2> + +<p>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 <a href="/en-US/Apps/Build/Offline">Offline</a> 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.<br> + <br> + 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 <a href="http://alistapart.com/article/application-cache-is-a-douchebag">Application Cache is a Douchebag</a> untuk lebih detail.</p> + +<div class="note"> +<p><strong>Catatan</strong>: Pada firefox 44, ketika <a href="/en-US/docs/Web/HTML/Using_the_application_cache">AppCache</a> digunakan untuk menyediakan layanan offline untuk suatu halaman, pesan peringatan sekarang akan ditampilkan di console menyarankan pengembang untuk menggunakan <a href="/en-US/docs/Web/API/Service_Worker_API/Using_Service_Workers">Service workers</a> ({{bug("1204581")}}.)</p> +</div> + +<p>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 <a href="http://offlinefirst.org/">Offline First</a>). Ini sudah tersedia dengan aplikasi asli, yang merupakan salah satu alasan utama aplikasi asli sering dipilih lebih dari aplikasi web.</p> + +<h2 id="Persiapan_bermain_dengan_service_worker">Persiapan bermain dengan service worker</h2> + +<p>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:</p> + +<ul> + <li><strong>Firefox Nightly</strong>: Buka <code>about:config</code> dan atur <code>dom.serviceWorkers.enabled</code> ke true; kemudian restart browser.</li> + <li><strong>Chrome Canary</strong>: Buka <code>chrome://flags</code> dan aktifkan <code>experimental-web-platform-features</code>; restart browser ( perlu dicatat bahwa beberapa fitur telah diaktifkan secara default di Chrome.)</li> + <li><strong>Opera</strong>: Buka <code>opera://flags</code> dan aktifkan dukungan untuk<code> ServiceWorker</code>; restart browser.</li> +</ul> + +<p>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.</p> + +<h2 id="Arsitektur_dasar">Arsitektur dasar</h2> + +<p>Dengan service workers, langkah - langkah umum berikut perlu diamati untuk konfigurasi dasar:</p> + +<ol> + <li>URL service worker diambil di daftarkan melalui {{domxref("serviceWorkerContainer.register()")}}.</li> + <li>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.</li> + <li>Sekarang service worker telah siap untuk memproses event.</li> + <li>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.</li> + <li>Ketika handler <code>oninstall</code> selesai, service worker ditetapkan untuk diinstall.</li> + <li>Selanjutnya adalah aktivasi. Ketika service worker terinstall, selanjutnya akan menerima event activate. Penggunaan utama dari <code>onactivate</code> adalah untuk membersihkan sumberdaya yang digunakan pada versi sebelumnya.</li> + <li>Service Worker sekarang dapat mengontrol halaman, tapi hanya yang di buka setelah <code>register()</code> 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.</li> +</ol> + +<p><img alt="" src="https://mdn.mozillademos.org/files/12636/sw-lifecycle.png" style="display: block; height: 867px; margin: 0px auto; width: 579px;"></p> + +<p>Grafik dibawah menunjukan ringkasan dari event yang tersedia pada service worker:</p> + +<p><img alt="install, activate, message, fetch, sync, push" src="https://mdn.mozillademos.org/files/12632/sw-events.png" style="display: block; margin: 0px auto;"></p> + +<h3 id="Promis">Promis</h3> + +<p><a href="/id/docs/Web/JavaScript/Reference/Global_Objects/Promise">Promis</a> 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.<br> + <br> + Promis bisa digunakan untuk melakukan banyak hal, tapi untuk saat ini, yang perlu anda tahu adalah jika sesuatu yang mengembalikan promise, anda bisa menambahkan<code>.then()</code> di akhir dan menambahkan callback di dalamnya untuk mengetahui apakah berhasil, gagal da lainnya., atau anda bisa menambahkan <code>.catch()</code> di akhir jika anda ingin menambahkan calback status gagal.</p> + +<p>Mari bandingkan kesamaan struktur callback tradisional synchronous dan promise asynchronous.</p> + +<h4 id="sync">sync</h4> + +<pre class="brush: js">try { + var value = myFunction(); + console.log(value); +} catch(err) { + console.log(err); +}</pre> + +<h4 id="async">async</h4> + +<pre class="brush: js">myFunction().then(function(value) { + console.log(value); + }).catch(function(err) { + console.log(err); +});</pre> + +<p>Pada contoh pertama, kita perlu mengunggu <code>myFunction()</code> untuk dijalankan dan mengembalikan nilai sebelum kode lain bisa dijalankan. Pada contoh kedua, <code>myFunction()</code> mengembalikan promise untuk <code>nilai</code>, kemudian semua kode dapat di bawa untuk dapat dijalankan. Ketika promise diselesaikan, kode didalamnya bisa dijalankan secara asynchronously.<br> + <br> + 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 <code>.onload</code> untuk hanya menampilkan gambar setelah di muat, tapi bagaimana dengan event yang memulai sebelum kita memulai melacaknya ? kita bisa mencoba melakukannya dengan menggunakan<code>.complete</code>, tapi ini tetap tidak foolproof, dan bagaimana dengan lebih dari satu gambar? Dan, ummm, ini tetap synchronous, Jadi di blok di tread utama.<br> + <br> + Gantinya, kita bisa membuat promis kita sendiri untuk mengatasi kasus seperi ini. (Lihat contoh <a href="https://github.com/mdn/promises-test">Promises test</a> untuk kode sumber, atau <a href="https://mdn.github.io/promises-test/">Lihat cara kerja secara live</a>.)</p> + +<p>{{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.")}}</p> + +<pre class="brush: js">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(); + }); +}</pre> + +<p>Kita mengembalikan promis baru menggunakan konstruktor <code>Promise()</code>, di mana menggunakan argumen sebagai fungsi callback dengan parameter <code>resolve</code> dan <code>reject</code>. 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 <code>resolve</code> ketika sukses, atau <code>reject</code> jika gagal. Semua konten dari fungsi ini adalah perangkat dasar XHR, jadi kita tidak perlu khawatir untuk saat ini.</p> + +<p>Ketika memanggil fungsi <code>imgLoad()</code>, kita memanggilnya dengan menggunakan url gambar yang akan dimuat, seperti yang kita harapkan, namun kodenya sedikit berbeda:</p> + +<pre class="brush: js">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); +});</pre> + +<p>Pada akhir pemanggilan fungsi, kita menggabungkan promise method <code>then()</code>, 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 <code>myImage</code> dan menambahkannya ke body (dengan argumen <code>request.response</code> yang berada di dalam method <code>resolve</code>); pada kasus ditolak kita mengembalikan error di console.</p> + +<p>Semua terjadi secara asynchronously.</p> + +<div class="note"> +<p><strong>Catatan</strong>: Anda juga bisa menggabungkan panggilan promise secara bersamaan, Misal:<br> + <code>myPromise().then(success, failure).then(success).catch(failure);</code></p> +</div> + +<div class="note"> +<p><strong>Catatan</strong>: Anda bisa mendapatkan lebih banyak informasi tentang promise dengan membaca tulisan Jake Archibald’s excellent <a href="http://www.html5rocks.com/en/tutorials/es6/promises/">JavaScript Promises: there and back again</a>.</p> +</div> + +<h2 id="Demo_service_workers">Demo service workers</h2> + +<p>Sebagai demonstrasi hanya sekedar dasar pendaftaran dan penginstalan service worker, kita membuat sebuah demo sederhana dengan nama <a href="https://github.com/mdn/sw-test">sw-test</a>, 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!</p> + +<p><img alt="" src="https://mdn.mozillademos.org/files/8243/demo-screenshot.png" style="display: block; height: 410px; margin: 0px auto; width: 480px;"><br> + <br> + <br> + Anda bisa melihat <a href="https://github.com/mdn/sw-test/">source code di GitHub</a>, dan <a href="https://mdn.github.io/sw-test/">Melihat contoh secara live</a>. The one bit we’ll call out here is the promise (see <a href="https://github.com/mdn/sw-test/blob/gh-pages/app.js#L17-L42">app.js lines 17-42</a>), which is a modified version of what you read about above, in the <a href="https://github.com/mdn/promises-test">Promises test demo</a>. It is different in the following ways:</p> + +<ol> + <li>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 <a href="https://github.com/mdn/sw-test/blob/gh-pages/image-list.js">image-list.js</a>). 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 <code>for()</code> 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.)</li> + <li>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 <a href="https://github.com/mdn/sw-test/blob/gh-pages/app.js#L26-L29">app.js lines 26-29</a>). Promises will only resolve with a single argument, so if you want to resolve with multiple values, you need to use an array/object.</li> + <li>To access the resolved promise values, we then access this function as you’d then expect (see <a href="https://github.com/mdn/sw-test/blob/gh-pages/app.js#L55-L59">app.js lines 55-59</a>.) This may seem a bit odd at first, but this is the way promises work.</li> +</ol> + +<h2 id="Enter_Service_workers">Enter Service workers</h2> + +<p>Now let’s get on to service workers!</p> + +<h3 id="Mendaftarkan_worker">Mendaftarkan worker</h3> + +<p>The first block of code in our app’s JavaScript file — <code>app.js</code> — is as follows. This is our entry point into using service workers.</p> + +<pre class="brush: js">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); + }); +};</pre> + +<ol> + <li>The outer block performs a feature detection test to make sure service workers are supported before trying to register one.</li> + <li>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.)</li> + <li>The <code>scope</code> 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 '<code>/sw-test/'</code>, 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.</li> + <li>The <code>.then()</code> promise function is used to chain a success case onto our promise structure. When the promise resolves successfully, the code inside it executes.</li> + <li>Finally, we chain a <code>.catch()</code> function onto the end that will run if the promise is rejected.</li> +</ol> + +<p>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.<br> + <br> + 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.</p> + +<div class="note"> +<p><strong>Note</strong>: 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.</p> +</div> + +<div class="note"> +<p><strong>Note</strong>: 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.</p> +</div> + +<h4 id="Kenapa_service_worker_saya_gagal_didaftarkan">Kenapa service worker saya gagal didaftarkan?</h4> + +<p>Hal tersebut bisa terjadi karena alasan berikut:</p> + +<ol> + <li>Anda tidak menjalankan aplikasi dari HTTPS.</li> + <li>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 <code>https://mdn.github.io/sw-test/sw.js</code>, dan root aplikasi di <code>https://mdn.github.io/sw-test/</code>. Namun path harus ditulis <code>/sw-test/sw.js</code>, bukan <code>/sw.js</code>.</li> + <li>The service worker being pointed to is on a different origin to that of your app. This is also not allowed.</li> +</ol> + +<p><img alt="" src="https://mdn.mozillademos.org/files/12630/important-notes.png" style="display: block; height: 277px; margin: 0px auto; width: 574px;"></p> + +<p>Also note:</p> + +<ul> + <li>The service worker will only catch requests from clients under the service worker's scope.</li> + <li>The max scope for a service worker is the location of the worker.</li> + <li>If your server worker is active on a client being served with the <code>Service-Worker-Allowed</code> header, you can specify a list of max scopes for that worker.</li> + <li>In Firefox, Service Worker APIs are hidden and cannot be used when the user is in <a href="https://support.mozilla.org/en-US/kb/private-browsing-use-firefox-without-history">private browsing mode</a>.</li> +</ul> + +<h3 id="Install_dan_activasi_mengumpulkan_cache">Install dan activasi: mengumpulkan cache</h3> + +<p>Setelah service worker anda terdaftar, browser akan menginstall dan mengaktifkan service worker untuk halaman/situs anda.<br> + <br> + 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.</p> + +<div class="note"> +<p><strong>Note</strong>: 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 <a href="https://github.com/Polymer/topeka/blob/master/sw.js">Google's Topeka demo</a>, or perhaps store your assets in <a href="/en-US/docs/Web/API/IndexedDB_API">IndexedDB</a>.</p> +</div> + +<p>Let’s start this section by looking at a code sample — this is the <a href="https://github.com/mdn/sw-test/blob/gh-pages/sw.js#L1-L18">first block you’ll find in our service worker</a>:</p> + +<pre class="brush: js">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' + ]); + }) + ); +});</pre> + +<ol> + <li>Here we add an <code>install</code> event listener to the service worker (hence <code>this</code>), and then chain a {{domxref("ExtendableEvent.waitUntil()") }} method onto the event — this ensures that the Service Worker will not install until the code inside <code>waitUntil()</code> has successfully occurred.</li> + <li>Inside <code>waitUntil()</code> we use the <a href="/en-US/docs/Web/API/CacheStorage/open"><code>caches.open()</code></a> method to create a new cache called <code>v1</code>, 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 <code>addAll()</code> on the created cache, which for its parameter takes an array of origin-relative URLs to all the resources you want to cache.</li> + <li>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.</li> + <li>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.)</li> +</ol> + +<div class="note"> +<p><strong>Note</strong>: <a href="/en-US/docs/Web/Guide/API/DOM/Storage">localStorage</a> works in a similar way to service worker cache, but it is synchronous, so not allowed in service workers.</p> +</div> + +<div class="note"> +<p><strong>Note</strong>: <a href="/en-US/docs/Web/API/IndexedDB_API">IndexedDB</a> can be used inside a service worker for data storage if you require it.</p> +</div> + +<h3 id="Custom_responses_to_requests">Custom responses to requests</h3> + +<p>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 <code>fetch</code> event.</p> + +<p><img alt="" src="https://mdn.mozillademos.org/files/12634/sw-fetch.png" style="display: block; margin: 0 auto;"></p> + +<p>A <code>fetch</code> 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 <code>index.html</code> makes a cross origin request to embed an image, that still goes through its service worker.)</p> + +<p>You can attach a <code>fetch</code> event listener to the service worker, then call the <code>respondWith()</code> method on the event to hijack our HTTP responses and update them with your own magic.</p> + +<pre class="brush: js">this.addEventListener('fetch', function(event) { + event.respondWith( + // magic goes here + ); +});</pre> + +<p>We could start by simply responding with the resource whose url matches that of the network request, in each case:</p> + +<pre class="brush: js">this.addEventListener('fetch', function(event) { + event.respondWith( + caches.match(event.request); + ); +});</pre> + +<p><code>caches.match(event.request)</code> 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.</p> + +<p>Let’s look at a few other options we have when defining our magic (see our <a href="/en-US/docs/Web/API/Fetch_API">Fetch API documentation</a> for more information about {{domxref("Request")}} and {{domxref("Response")}} objects.)</p> + +<ol> + <li> + <p>The <code>{{domxref("Response.Response","Response()")}}</code> constructor allows you to create a custom response. In this case, we are just returning a simple text string:</p> + + <pre class="brush: js">new Response('Hello from your friendly neighbourhood service worker!');</pre> + </li> + <li> + <p>This more complex <code>Response</code> 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:</p> + + <pre class="brush: js">new Response('</pre> + + <p>Hello from your friendly neighbourhood service worker!</p> + ', { headers: { 'Content-Type': 'text/html' } })</li> + <li> + <p>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:</p> + + <pre class="brush: js">fetch(event.request)</pre> + </li> + <li> + <p>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:</p> + + <pre class="brush: js">caches.match('/fallback.html');</pre> + </li> + <li> + <p>You can retrieve a lot of information about each request by calling parameters of the {{domxref("Request")}} object returned by the {{domxref("FetchEvent")}}:</p> + + <pre class="brush: js">event.request.url +event.request.method +event.request.headers +event.request.body</pre> + </li> +</ol> + +<h2 id="Recovering_failed_requests">Recovering failed requests</h2> + +<p>So <code>caches.match(event.request)</code> 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.</p> + +<p>Fortunately service workers’ promise-based structure makes it trivial to provide further options towards success. We could do this:</p> + +<pre class="brush: js">this.addEventListener('fetch', function(event) { + event.respondWith( + caches.match(event.request).catch(function() { + return fetch(event.request); + }) + ); +});</pre> + +<p>If the promise rejects, the <code>catch()</code> 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.</p> + +<p>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:</p> + +<pre class="brush: js">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; + }); + }); + }) + ); +});</pre> + +<p>Here we return the default network request with <code>return fetch(event.request)</code>, which returns a promise. When this promise is resolved, we respond by running a function that grabs our cache using <code>caches.open('v1')</code>; this also returns a promise. When that promise resolves, <code>cache.put()</code> is used to add the resource to the cache. The resource is grabbed from <code>event.request</code>, and the response is then cloned with <code>response.clone()</code> 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.</p> + +<p>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.</p> + +<p>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:</p> + +<pre class="brush: js">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'); + }) + ); +});</pre> + +<p>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 <code>install</code> event listener we saw earlier.</p> + +<h2 id="Updated_code_pattern_suggestion">Updated code pattern suggestion</h2> + +<p>This uses more standard promise chaining and returns the response to the document without having to wait for <code>caches.open()</code> to resolve:</p> + +<pre class="brush: js">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'); + })); +});</pre> + +<h2 id="Membaharui_service_worker"><a id="Updating your service worker" name="Updating your service worker">Membaharui service worker</a></h2> + +<p>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.</p> + +<p>You’ll want to update your <code>install</code> event listener in the new service worker to something like this (notice the new version number):</p> + +<pre class="brush: js">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... + ]); + }); + ); +});</pre> + +<p>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 <code>v2</code>, so the previous <code>v1</code> cache isn't disturbed.</p> + +<p>When no pages are using the current version, the new worker activates and becomes responsible for fetches.</p> + +<h3 id="Deleting_old_caches">Deleting old caches</h3> + +<p>You also get an <code>activate</code> 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.</p> + +<p>Promises passed into <code>waitUntil()</code> 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 <code>fetch</code> event on the new cache.</p> + +<pre class="brush: js">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); + } + })); + }) + ); +});</pre> + +<h2 id="Dev_tools">Dev tools</h2> + +<p>Chrome has <code>chrome://inspect/#service-workers</code>, which shows current service worker activity and storage on a device, and <code>chrome://serviceworker-internals</code>, 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.</p> + +<p>Firefox has also started to implement some useful tools related to service workers:</p> + +<ul> + <li>You can navigate to <a>about:serviceworkers</a> to see what SWs are registered and update/remove them.</li> + <li>When testing you can get around the HTTPS restriction by checking the "Enable Service Workers over HTTP (when toolbox is open)" option in the Firefox Devtools options (gear menu.)</li> +</ul> + +<h2 id="Spesifikasi">Spesifikasi</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Spesifikasi</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('Service Workers', '')}}</td> + <td>{{Spec2('Service Workers')}}</td> + <td>Initial definition.</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Fitur</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari (WebKit)</th> + </tr> + <tr> + <td>Dukungan dasar</td> + <td>{{CompatChrome(40.0)}}</td> + <td>{{ CompatGeckoDesktop("33.0") }}<sup>[1]</sup></td> + <td>{{CompatNo}}</td> + <td>24</td> + <td>{{CompatNo}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Fitur</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>Firefox OS</th> + <th>IE Phone</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Dukungan dasar</td> + <td>{{CompatNo}}</td> + <td>{{CompatChrome(40.0)}}</td> + <td>{{ CompatVersionUnknown }}</td> + <td>{{ CompatVersionUnknown }}</td> + <td>{{CompatNo}}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{CompatNo}}</td> + </tr> + </tbody> +</table> +</div> + +<p>[1] Service workers (and <a href="/en-US/docs/Web/API/Push_API">Push</a>) have been disabled in the <a href="https://www.mozilla.org/en-US/firefox/organizations/">Firefox 45 Extended Support Release</a> (ESR.)</p> + +<h2 id="Lihat_juga">Lihat juga</h2> + +<ul> + <li><a href="https://serviceworke.rs/">The Service Worker Cookbook</a></li> + <li><a href="https://jakearchibald.github.io/isserviceworkerready/">Is ServiceWorker ready?</a></li> + <li>Download the <a href="https://mdn.mozillademos.org/files/12638/sw101.png">Service Workers 101 cheatsheet</a>.</li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise">Promises</a></li> + <li><a href="/en-US/docs/Web/Guide/Performance/Using_web_workers">Using web workers</a></li> +</ul> 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 +--- +<div>{{SeeCompatTable}}{{APIRef("Service Workers API")}}</div> + +<p>Antarmuka <code>ServiceWorker</code> dari <a href="/en-US/docs/Web/API/ServiceWorker_API">ServiceWorker API</a> menyediakan referensi kepada service worker. Konteks multi browsing (mis. halaman, pekerja, dll.) dapat dikaitkan dengan service worker yang sama, masing - masing melalui objek <code>ServiceWorker</code> tersendiri.</p> + +<p>Objek <code>ServiceWorker</code> 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.)</p> + +<p>Antarmuka <code>ServiceWorker</code> terbagi sebagai rangkaian siklus event — <code>install</code> dan <code>activate</code> — dan fungsional event termasuk <code>fetch</code>. Objek <code>ServiceWorker</code> memiliki keterkaitan {{domxref("ServiceWorker.state")}}, berdasarkan siklusnya.</p> + +<h2 id="Properti">Properti</h2> + +<p><em>Antarmuka <code>ServiceWorker</code> mewarisi properti dari induknya, {{domxref("Worker")}}.</em></p> + +<dl> + <dt>{{domxref("ServiceWorker.scriptURL")}} {{readonlyinline}}</dt> + <dd>Mengembalikan serialisasi script URL <code>ServiceWorker</code> didefinisikan sebagai bagian dari {{domxref("ServiceWorkerRegistration")}}. URL harus dari origin yang sama dengan dokumen yang mendaftarkan <code>ServiceWorker</code>.</dd> + <dt>{{domxref("ServiceWorker.state")}} {{readonlyinline}}</dt> + <dd>Mengembalikan status keadaan service worker. Akan mengembalikan salah satu dari nilai berikut: <code>installing</code>, <code>installed,</code> <code>activating</code>, <code>activated</code>, atau <code>redundant</code>.</dd> +</dl> + +<h3 id="Event_handlers">Event handlers</h3> + +<dl> + <dt>{{domxref("ServiceWorker.onstatechange")}} {{readonlyinline}}</dt> + <dd>Properti {{domxref("EventListener")}} dipanggil setiap kali event type <code>statechange</code> di jalankan; Pada dasarnya dijalankan setiap ada perubahan pada {{domxref("ServiceWorker.state")}}.</dd> +</dl> + +<h2 id="Method">Method</h2> + +<p><em>Antarmuka <code>ServiceWorker</code> mewarisi method dari induknya, {{domxref("Worker")}}, dengan pengecualian {{domxref("Worker.terminate")}} — tidak harus dapat diakses dari service workers.</em></p> + +<h2 id="Contoh">Contoh</h2> + +<p>Ini adalah potongan kode dari <a href="https://github.com/GoogleChrome/samples/blob/gh-pages/service-worker/registration-events/index.html">service worker registration-events sample</a> (<a href="https://googlechrome.github.io/samples/service-worker/registration-events/">live demo</a>). Kode memperhatikan setiap perubahan di {{domxref("ServiceWorker.state")}} dan mengembalikan nilainya.</p> + +<pre class="brush: js">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. +}</pre> + +<h2 id="Spesifikasi">Spesifikasi</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Spesifikasi</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('Service Workers', '#service-worker-obj', 'ServiceWorker')}}</td> + <td>{{Spec2('Service Workers')}}</td> + <td>Definisi inisial</td> + </tr> + </tbody> +</table> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Fitur</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari (WebKit)</th> + </tr> + <tr> + <td>Dukungan dasar</td> + <td>{{CompatChrome(40.0)}}</td> + <td>{{CompatGeckoDesktop("44.0")}}<sup>[1]</sup></td> + <td>{{CompatNo}}</td> + <td>24</td> + <td>{{CompatNo}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Fitur</th> + <th>Android</th> + <th>Android Webview</th> + <th>Firefox Mobile (Gecko)</th> + <th>Firefox OS</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + <th>Chrome for Android</th> + </tr> + <tr> + <td>Dukungan dasar</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatGeckoMobile("44.0")}}</td> + <td>{{ CompatVersionUnknown }}</td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatChrome(40.0)}}</td> + </tr> + </tbody> +</table> +</div> + +<p>[1] Service workers (dan <a href="/en-US/docs/Web/API/Push_API">Push</a>) telah di nonaktifkan di <a href="https://www.mozilla.org/en-US/firefox/organizations/">Firefox 45 Extended Support Release</a> (ESR.)</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="https://serviceworke.rs">ServiceWorker Cookbook</a></li> + <li><a href="/id/docs/Web/API/ServiceWorker_API/Using_Service_Workers">Menggunakan Service Workers</a></li> + <li><a href="https://github.com/mdn/sw-test">Contoh kode dasar Service workers</a></li> + <li><a href="https://jakearchibald.github.io/isserviceworkerready/">Is ServiceWorker ready?</a></li> + <li>{{jsxref("Promise", "Promises")}}</li> + <li><a href="/id/docs/Web/Guide/Performance/Using_web_workers">Menggunakan web worker</a></li> +</ul> 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 +--- +<p>{{APIRef("Service Workers API")}}</p> + +<p><span class="seoSummary">The <code>ServiceWorkerContainer</code> interface of the <a href="/en-US/docs/Web/API/Service_Worker_API">Service Worker API</a> 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.</span></p> + +<p>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.</p> + +<h2 id="Properties">Properties</h2> + +<dl> + <dt>{{domxref("ServiceWorkerContainer.controller")}} {{readonlyinline}}</dt> + <dd>Returns a {{domxref("ServiceWorker")}} object if its state is <code>activated</code> (the same object returned by {{domxref("ServiceWorkerRegistration.active")}}). This property returns <code>null</code> during a force-refresh request (<em>Shift</em> + refresh) or if there is no active worker.</dd> +</dl> + +<dl> + <dt>{{domxref("ServiceWorkerContainer.ready")}} {{readonlyinline}}</dt> + <dd>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")}}.</dd> +</dl> + +<h2 id="Events">Events</h2> + +<dl> + <dt><code>controllerchange</code></dt> + <dd>Occurs when the document's associated {{domxref("ServiceWorkerRegistration")}} acquires a new {{domxref("ServiceWorkerRegistration.active","active")}} worker.<br> + Also available via the {{domxref("ServiceWorkerContainer.oncontrollerchange")}} property.</dd> + <dt><code>error</code></dt> + <dd>Fired whenever an error occurs in the associated service workers.<br> + Also available via the {{domxref("ServiceWorkerContainer.onerror")}} property.</dd> + <dt><code><a href="/en-US/docs/Web/API/ServiceWorkerContainer/message_event">message</a></code></dt> + <dd>Occurs when incoming messages are received by the {{domxref("ServiceWorkerContainer")}} object (e.g. via a {{domxref("MessagePort.postMessage()")}} call.)<br> + Also available via the {{domxref("ServiceWorkerContainer.onmessage")}} property.</dd> +</dl> + +<h2 id="Methods">Methods</h2> + +<dl> + <dt>{{domxref("ServiceWorkerContainer.register", "ServiceWorkerContainer.register()")}} </dt> + <dd>Creates or updates a {{domxref("ServiceWorkerRegistration")}} for the given <code>scriptURL</code>.</dd> + <dt>{{domxref("ServiceWorkerContainer.getRegistration()")}}</dt> + <dd>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 <code>undefined</code>. </dd> + <dt>{{domxref("ServiceWorkerContainer.getRegistrations()")}}</dt> + <dd>Returns all {{domxref("ServiceWorkerRegistration")}} objects associated with a <code>ServiceWorkerContainer</code> in an array. The method returns a {{jsxref("Promise")}} that resolves to an array of {{domxref("ServiceWorkerRegistration")}}. </dd> + <dt>{{domxref("ServiceWorkerContainer.startMessages()")}}</dt> + <dd>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.</dd> +</dl> + +<h2 id="Examples">Examples</h2> + +<p>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.</p> + +<pre class="brush: js notranslate">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.'); +}</pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('Service Workers', '#serviceworkercontainer', 'ServiceWorkerContainer')}}</td> + <td>{{Spec2('Service Workers')}}</td> + <td>Initial definition.</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<div> + + +<p>{{Compat("api.ServiceWorkerContainer")}}</p> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="/en-US/docs/Web/API/Service_Worker_API/Using_Service_Workers">Using Service Workers</a></li> + <li><a class="external external-icon" href="https://github.com/mdn/sw-test">Service workers basic code example</a></li> + <li><a class="external external-icon" href="https://jakearchibald.github.io/isserviceworkerready/">Is ServiceWorker ready?</a></li> + <li>{{jsxref("Promise")}}</li> + <li><a href="/en-US/docs/Web/API/Web_Workers_API/Using_web_workers">Using web workers</a></li> +</ul> 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 +--- +<div> +<div>{{SeeCompatTable}}{{APIRef("Service Workers API")}}</div> +</div> + +<p>The <code>ServiceWorkerRegistration</code> interface of the <a href="/en-US/docs/Web/API/ServiceWorker_API">ServiceWorker API</a> represents the service worker registration. You register a service worker to control one or more pages that share the same origin.</p> + +<p>The lifetime of a service worker registration is beyond that of the <code>ServiceWorkerRegistration</code> objects that represent them within the lifetime of their corresponding service worker clients. The browser maintains a persistent list of active <code>ServiceWorkerRegistration</code> objects.</p> + +<div class="note"> +<p><strong>Note</strong>: This feature is available in <a href="/en-US/docs/Web/API/Web_Workers_API">Web Workers</a>.</p> +</div> + +<h2 id="Properties">Properties</h2> + +<p><em>Also implements properties from its parent interface, </em>{{domxref("EventTarget")}}.</p> + +<dl> + <dt>{{domxref("ServiceWorkerRegistration.scope")}} {{readonlyinline}}</dt> + <dd>Returns a unique identifier for a service worker registration. This must be on the same origin as the document that registers the {{domxref("ServiceWorker")}}.</dd> + <dt>{{domxref("ServiceWorkerRegistration.installing")}} <strong style="font-weight: bold;">{{readonlyinline}}</strong></dt> + <dd>Returns a service worker whose state is <code>installing</code>. This is initially set to <code>null</code>.</dd> + <dt>{{domxref("ServiceWorkerRegistration.waiting")}} <strong style="font-weight: bold;">{{readonlyinline}}</strong></dt> + <dd>Returns a service worker whose state is <code>installed</code>. This is initially set to <code>null</code>.</dd> + <dt>{{domxref("ServiceWorkerRegistration.active")}} <strong style="font-weight: bold;">{{readonlyinline}}</strong></dt> + <dd>Returns a service worker whose state is either <code>activating</code> or <code>activated</code>. This is initially set to <code>null</code>. An active worker will control a {{domxref("ServiceWorkerClient")}} if the client's URL falls within the scope of the registration (the <code>scope</code> option set when {{domxref("ServiceWorkerContainer.register")}} is first called.)</dd> + <dt>{{domxref("serviceWorkerRegistration.periodicSync")}} {{non-standard_inline}} {{readonlyinline}}</dt> + <dd>Returns a reference to the {{domxref("PeriodicSyncManager")}} interface, which manages periodic background synchronization processes.</dd> + <dt>{{domxref("ServiceWorkerRegistration.pushManager")}} {{readonlyinline}}</dt> + <dd>Returns a reference to the {{domxref("PushManager")}} interface for managing push subscriptions including subscribing, getting an active subscription, and accessing push permission status.</dd> + <dt>{{domxref("ServiceWorkerRegistration.sync")}} <strong style="font-weight: bold; line-height: 19.0909080505371px;">{{non-standard_inline}} </strong>{{readonlyinline}} </dt> + <dd>Returns a reference to the {{domxref("SyncManager")}} interface, which manages background synchronization processes.</dd> +</dl> + +<h3 id="Event_handlers">Event handlers</h3> + +<dl> + <dt>{{domxref("ServiceWorkerRegistration.onupdatefound")}} {{readonlyinline}}</dt> + <dd>An <a href="https://developer.mozilla.org/en-US/docs/Web/API/EventListener" title="This method is called whenever an event occurs of the type for which the EventListener interface was registered."><code>EventListener</code></a> property called whenever an event of type <code>updatefound</code> is fired; it is fired any time the {{domxref("ServiceWorkerRegistration.installing")}} property acquires a new service worker.</dd> +</dl> + +<h2 id="Methods">Methods</h2> + +<p><em>Also implements methods from its parent interface, </em>{{domxref("EventTarget")}}.</p> + +<dl> + <dt>{{domxref("ServiceWorkerRegistration.getNotifications()")}}</dt> + <dd>Returns a {{jsxref("Promise")}} that resolves to an array of {{domxref("Notification")}} objects.</dd> + <dt>{{domxref("ServiceWorkerRegistration.showNotification()")}}</dt> + <dd>Displays the notification with the requested title.</dd> + <dt>{{domxref("ServiceWorkerRegistration.update()")}}</dt> + <dd>Checks the server for an updated version of the service worker without consulting caches.</dd> + <dt>{{domxref("ServiceWorkerRegistration.unregister()")}}</dt> + <dd>Unregisters the service worker registration and returns a promise (see {{jsxref("Promise")}}). The service worker will finish any ongoing operations before it is unregistered.</dd> +</dl> + +<h2 id="Examples">Examples</h2> + +<p>This code snippet is from the <a href="https://github.com/GoogleChrome/samples/blob/gh-pages/service-worker/registration-events/index.html">service worker registration-events sample</a> (<a class="external external-icon" href="https://googlechrome.github.io/samples/service-worker/registration-events/">live demo</a>). 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.</p> + +<p>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.</p> + +<pre class="brush: js">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'; +}</pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('Service Workers', '#service-worker-registration-obj', 'ServiceWorkerRegistration')}}</td> + <td>{{Spec2('Service Workers')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('Push API', '#widl-ServiceWorkerRegistration-pushManager', 'PushManager')}}</td> + <td>{{Spec2('Push API')}}</td> + <td>Adds the {{domxref("PushManager","pushManager")}} property.</td> + </tr> + <tr> + <td>{{SpecName('Web Notifications')}}</td> + <td>{{Spec2('Web Notifications')}}</td> + <td>Adds the {{domxref("ServiceWorkerRegistration.showNotification()","showNotification()")}} method and the {{domxref("ServiceWorkerRegistration.getNotifications()","getNotifications()")}} method.</td> + </tr> + <tr> + <td>{{SpecName('Background Sync')}}</td> + <td>{{Spec2('Background Sync')}}</td> + <td>Adds the {{domxref("ServiceWorkerRegistration.sync","sync")}} property.</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari (WebKit)</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatChrome(40.0)}}</td> + <td>{{ CompatGeckoDesktop("44.0") }}<sup>[1]</sup></td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td>Available in web workers</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop("44.0")}}<sup>[1]</sup></td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td><code>getNotifications()</code>, <code>showNotification()</code></td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop("46.0")}}<sup>[1]</sup></td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td><code>sync</code> property</td> + <td>{{CompatChrome(49.0)}}</td> + <td> </td> + <td> </td> + <td> </td> + <td> </td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Android Webview</th> + <th>Firefox Mobile (Gecko)</th> + <th>Firefox OS</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + <th>Chrome for Android</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{ CompatGeckoMobile("44.0") }}</td> + <td>{{ CompatVersionUnknown }}</td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatChrome(40.0)}}</td> + </tr> + <tr> + <td>Available in web workers</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatGeckoMobile("44.0")}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td><code>getNotifications()</code>, <code>showNotification()</code></td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatGeckoMobile("46.0")}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td><code>sync</code> property</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td> </td> + <td> </td> + <td> </td> + <td> </td> + <td> </td> + <td>{{CompatChrome(49.0)}}</td> + </tr> + </tbody> +</table> +</div> + +<p>[1] Service workers (and <a href="/en-US/docs/Web/API/Push_API">Push</a>) have been disabled in the <a href="https://www.mozilla.org/en-US/firefox/organizations/">Firefox 45 Extended Support Release</a> (ESR.)</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="/en-US/docs/Web/API/ServiceWorker_API/Using_Service_Workers">Using Service Workers</a></li> + <li><a href="https://github.com/mdn/sw-test">Service workers basic code example</a></li> + <li><a href="https://jakearchibald.github.io/isserviceworkerready/">Is ServiceWorker ready?</a></li> + <li>{{jsxref("Promise")}}</li> + <li><a href="/en-US/docs/Web/Guide/Performance/Using_web_workers">Using web workers</a></li> +</ul> 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 +--- +<div>{{SeeCompatTable}}{{APIRef("Service Workers API")}}</div> + +<p>Properti <strong><code>pushManager</code></strong> 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.</p> + +<h2 id="Syntax" name="Syntax" style="line-height: 30px; font-size: 2.14285714285714rem;">Sintaks</h2> + +<pre class="syntaxbox" style="font-size: 14px;">myPushManager = ServiceWorker.pushManager +</pre> + +<h3 id="Value">Value</h3> + +<p>Objek {{domxref("PushManager")}}.</p> + +<h2 id="Contoh">Contoh</h2> + +<pre class="brush: js">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); + } + ); + });</pre> + +<h2 id="Spesifikasi">Spesifikasi</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('Push API', '#pushmanager-interface', 'PushManager')}}</td> + <td>{{Spec2('Push API')}}</td> + <td>Initial definition.</td> + </tr> + </tbody> +</table> + +<h2 id="Kompabilitas_Browser">Kompabilitas Browser</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari (WebKit)</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatChrome(42.0)}}</td> + <td>{{ CompatGeckoDesktop("44.0") }}<sup>[1]</sup></td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatNo}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Android Webview</th> + <th>Firefox Mobile (Gecko)</th> + <th>Firefox OS</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + <th>Chrome for Android</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatChrome(42.0)}}</td> + </tr> + </tbody> +</table> +</div> + +<p>[1] Service workers (dan <a href="/en-US/docs/Web/API/Push_API">Push</a>) telah dinonaktifkan di <a href="https://www.mozilla.org/en-US/firefox/organizations/">Firefox 45 Extended Support Release</a> (ESR.)</p> + +<h2 id="Lihat_Juga">Lihat Juga</h2> + +<ul> + <li><a href="/en-US/docs/Web/API/Push_API">Push API</a></li> +</ul> 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 +--- +<p>{{APIRef("Web Speech API")}}{{SeeCompatTable}}</p> + +<p>The <strong><code>SpeechSynthesis</code></strong> interface of the <a href="/en-US/docs/Web/API/Web_Speech_API">Web Speech API</a> 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.</p> + +<h2 id="Properties">Properties</h2> + +<p><em><code>SpeechSynthesis</code> also inherits properties from its parent interface, {{domxref("EventTarget")}}.</em></p> + +<dl> + <dt>{{domxref("SpeechSynthesis.paused")}} {{readonlyinline}}</dt> + <dd>A {{domxref("Boolean")}} that returns <code>true</code> if the <code>SpeechSynthesis</code> object is in a paused state.</dd> + <dt>{{domxref("SpeechSynthesis.pending")}} {{readonlyinline}}</dt> + <dd>A {{domxref("Boolean")}} that returns <code>true</code> if the utterance queue contains as-yet-unspoken utterances.</dd> + <dt>{{domxref("SpeechSynthesis.speaking")}} {{readonlyinline}}</dt> + <dd>A {{domxref("Boolean")}} that returns <code>true</code> if an utterance is currently in the process of being spoken — even if <code>SpeechSynthesis</code> is in a paused state.</dd> +</dl> + +<dl> +</dl> + +<h2 id="Methods">Methods</h2> + +<p><em><code>SpeechSynthesis</code> also inherits methods from its parent interface, {{domxref("EventTarget")}}.</em></p> + +<dl> + <dt>{{domxref("SpeechSynthesis.cancel()")}}</dt> + <dd>Removes all utterances from the utterance queue.</dd> + <dt>{{domxref("SpeechSynthesis.getVoices()")}}</dt> + <dd>Returns a list of {{domxref("SpeechSynthesisVoice")}} objects representing all the available voices on the current device.</dd> + <dt>{{domxref("SpeechSynthesis.pause()")}}</dt> + <dd>Puts the <code>SpeechSynthesis</code> object into a paused state.</dd> + <dt>{{domxref("SpeechSynthesis.resume()")}}</dt> + <dd>Puts the <code>SpeechSynthesis</code> object into a non-paused state: resumes it if it was already paused.</dd> + <dt>{{domxref("SpeechSynthesis.speak()")}}</dt> + <dd>Adds an {{domxref("SpeechSynthesisUtterance", "utterance")}} to the utterance queue; it will be spoken when any other utterances queued before it have been spoken.</dd> +</dl> + +<h2 id="Events">Events</h2> + +<p>Listen to this event using <code><a href="/en-US/docs/Web/API/EventTarget/addEventListener">addEventListener()</a></code> or by assigning an event listener to the <code>on<em>eventname</em></code> property of this interface.</p> + +<dl> + <dt><code><a href="/en-US/docs/Web/API/SpeechSynthesis/voiceschanged_event">voiceschanged</a></code></dt> + <dd>Fired when the list of {{domxref("SpeechSynthesisVoice")}} objects that would be returned by the {{domxref("SpeechSynthesis.getVoices()")}} method has changed.<br> + Also available via the <code><a href="/en-US/docs/Web/API/SpeechSynthesis/onvoiceschanged">onvoiceschanged</a></code> property.</dd> +</dl> + +<h2 id="Examples">Examples</h2> + +<p>In our basic <a href="https://github.com/mdn/web-speech-api/tree/master/speak-easy-synthesis">Speech synthesiser demo</a>, we first grab a reference to the SpeechSynthesis controller using <code>window.speechSynthesis</code>. 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.</p> + +<p>Inside the <code>inputForm.onsubmit</code> handler, we stop the form submitting with <a href="/en-US/docs/Web/API/Event/preventDefault">preventDefault()</a>, 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.</p> + +<pre class="brush: js">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(); +}</pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('Web Speech API', '#tts-section', 'SpeechSynthesis')}}</td> + <td>{{Spec2('Web Speech API')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<div> + + +<p>{{Compat("api.SpeechSynthesis")}}</p> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="/en-US/docs/Web/API/Web_Speech_API">Web Speech API</a></li> +</ul> 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 +--- +<div>{{APIRef("Web Speech API")}}{{SeeCompatTable}}</div> + +<p>The <code><strong>onvoiceschanged</strong></code> 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 <a href="/en-US/docs/Web/API/SpeechSynthesis/voiceschanged_event">voiceschanged</a> event fires.)</p> + +<p>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.</p> + +<h2 id="Syntax">Syntax</h2> + +<pre class="syntaxbox">speechSynthesisInstance.onvoiceschanged = function() { ... }; +</pre> + +<h2 id="Examples">Examples</h2> + +<p>This could be used to populate a list of voices that the user can choose between when the event fires (see our <a href="https://github.com/mdn/web-speech-api/blob/gh-pages/speak-easy-synthesis/script.js">Speak easy synthesis demo</a>.) 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.</p> + +<pre class="brush: js">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; +}</pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('Web Speech API', '#dom-speechsynthesis-onvoiceschanged', 'onvoiceschanged')}}</td> + <td>{{Spec2('Web Speech API')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<div> + + +<p>{{Compat("api.SpeechSynthesis.onvoiceschanged")}}</p> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="/en-US/docs/Web/API/Web_Speech_API">Web Speech API</a></li> +</ul> 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 +--- +<div>{{APIRef("Web Storage API")}}</div> + +<p>The <strong><code>Storage</code></strong> interface of the <a href="/en-US/docs/Web/API/Web_Storage_API">Web Storage API</a> provides access to a particular domain's session or local storage. It allows, for example, the addition, modification, or deletion of stored data items.</p> + +<p>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")}}.</p> + +<h2 id="Properties">Properties</h2> + +<dl> + <dt>{{domxref("Storage.length")}} {{readonlyInline}}</dt> + <dd>Returns an integer representing the number of data items stored in the <code>Storage</code> object.</dd> +</dl> + +<h2 id="Methods">Methods</h2> + +<dl> + <dt>{{domxref("Storage.key()")}}</dt> + <dd>When passed a number <code>n</code>, this method will return the name of the nth key in the storage.</dd> +</dl> + +<dl> + <dt>{{domxref("Storage.getItem()")}}</dt> + <dd>When passed a key name, will return that key's value.</dd> + <dt>{{domxref("Storage.setItem()")}}</dt> + <dd>When passed a key name and value, will add that key to the storage, or update that key's value if it already exists.</dd> + <dt>{{domxref("Storage.removeItem()")}}</dt> + <dd>When passed a key name, will remove that key from the storage.</dd> + <dt>{{domxref("Storage.clear()")}}</dt> + <dd>When invoked, will empty all keys out of the storage.</dd> +</dl> + +<h2 id="Examples">Examples</h2> + +<p>Here we access a <code>Storage</code> object by calling <code>localStorage</code>. We first test whether the local storage contains data items using <code>!localStorage.getItem('bgcolor')</code>. If it does, we run a function called <code>setStyles()</code> 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, <code>populateStorage()</code>, which uses {{domxref("Storage.setItem()")}} to set the item values, then runs <code>setStyles()</code>.</p> + +<pre class="brush: js">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); +}</pre> + +<div class="note"> +<p><strong>Note</strong>: To see this running as a complete working example, see our <a href="https://mdn.github.io/dom-examples/web-storage/">Web Storage Demo</a>.</p> +</div> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('HTML WHATWG', 'webstorage.html#the-storage-interface', 'Storage')}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + + + +<p>{{Compat("api.Storage")}}</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="/en-US/docs/Web/API/Web_Storage_API/Using_the_Web_Storage_API">Using the Web Storage API</a></li> + <li>{{domxref("Window.localStorage")}}</li> + <li>{{domxref("Window.sessionStorage")}}</li> + <li>{{domxref("CacheStorage")}}</li> +</ul> 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 +--- +<div>{{WebGLSidebar}}</div> + +<div class="summary"> +<p>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.</p> +</div> + +<p>Dukungan WebGL telah tersedia di <a href="/en-US/Firefox" title="Firefox 4 for developers">Firefox</a> 4+, <a href="http://www.google.com/chrome/" title="http://www.google.com/chrome/">Google Chrome</a> 9+, <a href="http://www.opera.com/" title="http://www.opera.com/">Opera</a> 12+, <a href="http://www.apple.com/safari/" title="http://www.apple.com/fr/safari/">Safari </a>5.1+ dan <a href="http://windows.microsoft.com/en-us/internet-explorer/browser-ie" title="http://windows.microsoft.com/en-us/internet-explorer/download-ie">Internet Explorer</a> 11+; namum, perangkat pengguna juga harus memiliki perangkat keras yang mendukung fitur ini.</p> + +<p>Elemen {{HTMLElement("canvas")}} juga digunakan oleh <a href="/id/docs/Web/API/Canvas_API">Canvas 2D</a> untuk menggambar grafik 2D pada halaman web.</p> + +<h2 id="Referensi">Referensi</h2> + +<h3 id="Standar_Antarmuka">Standar Antarmuka</h3> + +<div class="index"> +<ul> + <li>{{domxref("WebGLRenderingContext")}}</li> + <li>{{domxref("WebGL2RenderingContext")}} {{experimental_inline}}</li> + <li>{{domxref("WebGLActiveInfo")}}</li> + <li>{{domxref("WebGLBuffer")}}</li> + <li>{{domxref("WebGLContextEvent")}}</li> + <li>{{domxref("WebGLFramebuffer")}}</li> + <li>{{domxref("WebGLProgram")}}</li> + <li>{{domxref("WebGLQuery")}} {{experimental_inline}}</li> + <li>{{domxref("WebGLRenderbuffer")}}</li> + <li>{{domxref("WebGLSampler")}} {{experimental_inline}}</li> + <li>{{domxref("WebGLShader")}}</li> + <li>{{domxref("WebGLShaderPrecisionFormat")}}</li> + <li>{{domxref("WebGLSync")}} {{experimental_inline}}</li> + <li>{{domxref("WebGLTexture")}}</li> + <li>{{domxref("WebGLTransformFeedback")}} {{experimental_inline}}</li> + <li>{{domxref("WebGLUniformLocation")}}</li> + <li>{{domxref("WebGLVertexArrayObject")}} {{experimental_inline}}</li> +</ul> +</div> + +<h3 id="Ekstensi">Ekstensi</h3> + +<div class="index"> +<ul> + <li>{{domxref("ANGLE_instanced_arrays")}}</li> + <li>{{domxref("EXT_blend_minmax")}}</li> + <li>{{domxref("EXT_color_buffer_half_float")}}</li> + <li>{{domxref("EXT_disjoint_timer_query")}}</li> + <li>{{domxref("EXT_frag_depth")}}</li> + <li>{{domxref("EXT_sRGB")}}</li> + <li>{{domxref("EXT_shader_texture_lod")}}</li> + <li>{{domxref("EXT_texture_filter_anisotropic")}}</li> + <li>{{domxref("OES_element_index_uint")}}</li> + <li>{{domxref("OES_standard_derivatives")}}</li> + <li>{{domxref("OES_texture_float")}}</li> + <li>{{domxref("OES_texture_float_linear")}}</li> + <li>{{domxref("OES_texture_half_float")}}</li> + <li>{{domxref("OES_texture_half_float_linear")}}</li> + <li>{{domxref("OES_vertex_array_object")}}</li> + <li>{{domxref("WEBGL_color_buffer_float")}}</li> + <li>{{domxref("WEBGL_compressed_texture_atc")}}</li> + <li>{{domxref("WEBGL_compressed_texture_es3")}}</li> + <li>{{domxref("WEBGL_compressed_texture_etc1")}}</li> + <li>{{domxref("WEBGL_compressed_texture_pvrtc")}}</li> + <li>{{domxref("WEBGL_compressed_texture_s3tc")}}</li> + <li>{{domxref("WEBGL_debug_renderer_info")}}</li> + <li>{{domxref("WEBGL_debug_shaders")}}</li> + <li>{{domxref("WEBGL_depth_texture")}}</li> + <li>{{domxref("WEBGL_draw_buffers")}}</li> + <li>{{domxref("WEBGL_lose_context")}}</li> +</ul> +</div> + +<h3 id="Event">Event</h3> + +<ul> + <li>{{Event("webglcontextlost")}}</li> + <li>{{Event("webglcontextrestored")}}</li> + <li>{{Event("webglcontextcreationerror")}}</li> +</ul> + +<h3 id="Tipe_dan_konstanta">Tipe dan konstanta</h3> + +<ul> + <li><a href="/id/docs/Web/API/WebGL_API/Constants">WebGL constants</a></li> + <li><a href="/id/docs/Web/API/WebGL_API/Types">WebGL types</a></li> +</ul> + +<h2 id="Paduan_dan_tutorial">Paduan dan tutorial</h2> + +<ul> + <li><a href="/id/docs/Web/API/WebGL_API/Tutorial">WebGL tutorial</a>: Paduan untuk pemula mengenai konsep inti WebGL. Tempat yang disarankan untuk anda yang sebelumnya belum memiliki pengalaman di WebGL.</li> + <li><a href="/id/docs/Web/API/WebGL_API/WebGL_best_practices">WebGL best practices</a>: Tips dan saran untuk meningkatkan konten WebGL anda.</li> + <li><a href="/id/docs/Web/API/WebGL_API/Using_Extensions">Using extensions</a>: Cara menggunakan Ekstensi yang tersedia di WebGL.</li> +</ul> + +<h3 id="Tutorial_lanjutan">Tutorial lanjutan</h3> + +<ul> + <li><a href="/id/docs/Web/API/WebGL_API/WebGL_model_view_projection">WebGL model view projection</a>: Penjelasan rinci dari tiga inti matrik yang biasa digunakan untuk mewakili pandangan objek 3D: model, pandangan dan proyeksi matrik.</li> + <li><a href="/id/docs/Web/API/WebGL_API/Matrix_math_for_the_web">Matrix math for the web</a>: Paduan mengetahui cara matrik 3D transform bekerja, dan bisa digunakan di web — baik untuk kalkulasi untuk WebGL dan CSS3 transforms.</li> +</ul> + +<h2 id="Sumber">Sumber</h2> + +<ul> + <li><a href="https://www.youtube.com/embed/H4c8t6myAWU/?feature=player_detailpage">Raw WebGL: Mengenal WebGL</a> Bahasan dari Nick Desaulniers yang memperkenalkan dasar WebGL. Tempat yang disarankan jika anda belum pernah mencoba pemrogrman grafis.</li> + <li><a href="http://www.khronos.org/webgl/" title="http://www.khronos.org/webgl/">Situs Khronos WebGL</a> Website utama WebGL di Khronos Group.</li> + <li><a href="http://learningwebgl.com/blog/?page_id=1217" title="http://learningwebgl.com/blog/">Belajar WebGL</a> Situs tutorial tentang cara menggunakan WebGL.</li> + <li><a href="http://www.html5rocks.com/en/tutorials/webgl/webgl_fundamentals/" title="http://www.html5rocks.com/en/tutorials/webgl/webgl_fundamentals/">WebGL Fundamental</a> Tutorial dasar dan fundamental WebGL.</li> + <li><a href="http://webglplayground.net" title="http://webglplayground.net">WebGL playground</a> Alat online untuk membuat dan berbagi proyek WebGL. Disarankan untuk percobaan dan eksperimen.</li> + <li><a href="http://www.webglacademy.com" title="http://www.webglacademy.com">WebGL Academy</a> Sebuah editor HTML/JavaScript dengan tutorial untuk belajar dasar pemrograman WebGL.</li> + <li><a href="http://webglstats.com/">WebGL Stats</a> Situs dengan statistik tentang kemampuan WebGL di browser pada platform yang berbeda.</li> +</ul> + +<h3 id="Pustaka">Pustaka</h3> + +<ul> + <li><a class="link-https" href="https://github.com/toji/gl-matrix" title="https://github.com/toji/gl-matrix">glMatrix</a> Pustaka JavaScript Matrix dan Vector untuk aplikasi WebGL dengan performa tinggi</li> + <li><a href="http://sylvester.jcoglan.com/" title="http://sylvester.jcoglan.com/">Sylvester</a> Pustaka open source untuk memanipulasi matrik dan vektor. Tidak di optimalkan untuk WebGL namun sangat kuat.</li> +</ul> + +<h2 id="Spesifikasi">Spesifikasi</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Spesifikasi</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('WebGL')}}</td> + <td>{{Spec2('WebGL')}}</td> + <td>Initial definition. Based on OpenGL ES 2.0</td> + </tr> + <tr> + <td>{{SpecName('WebGL2')}}</td> + <td>{{Spec2('WebGL2')}}</td> + <td>Builds on top of WebGL1. Based on OpenGL ES 3.0.</td> + </tr> + <tr> + <td>{{SpecName('OpenGL ES 2.0')}}</td> + <td>{{Spec2('OpenGL ES 2.0')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('OpenGL ES 3.0')}}</td> + <td>{{Spec2('OpenGL ES 3.0')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Kompabilitas_browser">Kompabilitas browser</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Firefox (Gecko)</th> + <th>Chrome</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatGeckoDesktop("2.0")}}</td> + <td>9</td> + <td>11</td> + <td>12<sup>[1]</sup></td> + <td>5.1<sup>[1]</sup></td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Firefox Mobile (Gecko)</th> + <th>Chrome for Android</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>4</td> + <td>25<sup>[1]</sup></td> + <td>{{CompatNo}}</td> + <td>12<sup>[1]</sup></td> + <td>8.1</td> + </tr> + </tbody> +</table> +</div> + +<p>[1] Implementasi dari fitur ini adalah eksperimental.</p> + +<h3 id="Catatan_kompabilitas">Catatan kompabilitas</h3> + +<p>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 <code>webgl</code>, tapi untuk yang lebih lama juga memerlukan <code>experimental-webgl</code>. Selain itu , nantinya <a href="/en-US/docs/Web/API/WebGL2RenderingContext">WebGL 2</a> sepenuhnya kompitable dengan yang sebelumnya dan akan memiliki nama konteks <code>webgl2</code>.</p> + +<h3 id="Catatan_Gecko">Catatan Gecko</h3> + +<h4 id="Pengujian_dan_debungging_WebGL">Pengujian dan debungging WebGL</h4> + +<p>Dimulai dari Gecko 10.0 {{geckoRelease("10.0")}}, disana tersedia dua pengaturan yang memungkinkan anda mengontrol kemampuan WebGL untuk keperluan percobaan:</p> + +<dl> + <dt><code>webgl.min_capability_mode</code></dt> + <dd>Properti Boolean yang, jika <code>true</code>, 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 <code>false</code>.</dd> + <dt><code>webgl.disable_extensions</code></dt> + <dd>Properti Boolean yang, jika <code>true</code>, menonaktifkan semua ekstensi WebGL. Nilai defaultnya <code>false</code>.</dd> +</dl> + +<h2 id="Lihat_Juga">Lihat Juga</h2> + +<ul> + <li><a href="/en-US/docs/Web/API/Canvas_API">Canvas</a></li> + <li><a href="https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getSupportedExtensions#Browser_compatibility">Compatibility info about WebGL extensions</a></li> +</ul> 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 +--- +<div>{{APIRef("WebRTC")}}</div> + +<p><span class="seoSummary"><strong>WebRTC</strong> (<em>Web Real-Time Communications</em>) 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.</span> Kumpulan standar di dalam WebRTC membuat pertukaran data dan telekonferensi secara <em>peer-to-peer</em> dapat terjadi tanpa perlu memasang <em>plugins</em> atau aplikasi pihak ketiga.</p> + +<p>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.</p> + +<h2 id="Konsep_dan_cara_penggunaan_WebRTC">Konsep dan cara penggunaan WebRTC</h2> + +<p>WebRTC memiliki beberapa fungsi, begitu halnya juga dengan <em>Media Capture and Streams</em> ({{domxref("MediaDevices")}}) API. Keduanya menghadirkan kemampuan multimedia di dalam web, misalnya audio dan video <em>conferencing</em>, pertukaran <em>file</em>, <em>identity management</em>, serta interaksi pada jaringan telepon dengan cara mengirimkan sinyal {{Glossary("DTMF")}}. Sambungan antar <em>peer</em> dapat terbentuk tanpa <em>plugins</em> tambahan, dan sering kali dapat terbentuk tanpa memerlukan <em>server</em> perantara.</p> + +<p>Sambungan antar <em>peer</em> dibuat menggunakan - dan direpresentasikan oleh - {{domxref("RTCPeerConnection")}}. Ketika sebuah sambungan telah terbentuk dan terbuka, <em>stream</em> media ({{domxref("MediaStream")}}) atau <em>channel</em> data ({{domxref("RTCDataChannel")}}) dapat ditambahkan ke dalam sambungan <em>peer</em>.</p> + +<p><em>Stream</em> media terdiri dari beberapa <em>track</em> media, yang direpresentasikan oleh sebuah objek {{domxref("MediaStreamTrack")}}, yang berisi salah satu tipe media, yaitu audio, video, dan teks (misalnya <em>subtitle</em> atau nama judul). Umumnya <em>stream</em> terdiri dari setidaknya satu <em>track</em> audio bahkan juga satu <em>track</em> video, dan dapat digunakan untuk mengirim dan menerima media secara <em>live</em> atau dapat berupa rekaman media (misalnya <em>streaming</em> film).</p> + +<p>Anda juga dapat menggunakan sambungan antar <em>peer</em> untuk bertukar sembarang data biner menggunakan {{domxref("RTCDataChannel")}}. Sambungan ini dapat digunakan untuk informasi <em>back-channel</em>, <em>metadata</em>, <em>gaming</em>, <em>file transfer</em>, bahkan sebagai jalur utama pertukaran data.</p> + +<p><em><strong>artikel ini memerlukan informasi yang lebih lanjut serta tautan untuk panduan dan tutorial yang relevan</strong></em></p> + +<h2 id="WebRTC_interfaces">WebRTC interfaces</h2> + +<p>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.</p> + +<h3 id="Connection_setup_and_management">Connection setup and management</h3> + +<p>These interfaces are used to set up, open, and manage WebRTC connections.</p> + +<dl> + <dt>{{domxref("RTCPeerConnection")}}</dt> + <dd>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.</dd> + <dt>{{domxref("RTCDataChannel")}}</dt> + <dd>Represents a bi-directional data channel between two peers of a connection.</dd> + <dt>{{domxref("RTCDataChannelEvent")}}</dt> + <dd>Represents events that occur while attaching a {{domxref("RTCDataChannel")}} to a {{domxref("RTCPeerConnection")}}. The only event sent with this interface is {{event("datachannel")}}.</dd> + <dt>{{domxref("RTCSessionDescription")}}</dt> + <dd>Represents the parameters of a session. Each <code>RTCSessionDescription</code> consists of a description <a href="/en-US/docs/Web/API/RTCSessionDescription/type" title="The property RTCSessionDescription.type is an enum of type RTCSdpType describing the description's type."><code>type</code></a> indicating which part of the offer/answer negotiation process it describes and of the <a href="/en-US/docs/Glossary/SDP" title="SDP: SDP (Session Description Protocol) is the standard describing a peer-to-peer connection. SDP contains the codec, source address, and timing information of audio and video.">SDP</a> descriptor of the session.</dd> + <dt>{{domxref("RTCStatsReport")}}</dt> + <dd>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()")}}.</dd> + <dt>{{domxref("RTCIceCandidate")}}</dt> + <dd>Represents a candidate internet connectivity establishment (ICE) server for establishing an {{domxref("RTCPeerConnection")}}.</dd> + <dt>{{domxref("RTCIceTransport")}}</dt> + <dd>Represents information about an internet connectivity establishment (ICE) transport.</dd> + <dt>{{domxref("RTCPeerConnectionIceEvent")}}</dt> + <dd>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")}}.</dd> + <dt>{{domxref("RTCRtpSender")}}</dt> + <dd>Manages the encoding and transmission of data for a {{domxref("MediaStreamTrack")}} on an {{domxref("RTCPeerConnection")}}.</dd> + <dt>{{domxref("RTCRtpReceiver")}}</dt> + <dd>Manages the reception and decoding of data for a {{domxref("MediaStreamTrack")}} on an {{domxref("RTCPeerConnection")}}.</dd> + <dt>{{domxref("RTCTrackEvent")}}</dt> + <dd>Indicates that a new incoming {{domxref("MediaStreamTrack")}} was created and an associated {{domxref("RTCRtpReceiver")}} object was added to the {{domxref("RTCPeerConnection")}} object.</dd> +</dl> + +<h3 id="Identity_and_security">Identity and security</h3> + +<p>The WebRTC API includes a number of interfaces to manage security and identity.</p> + +<dl> + <dt>{{domxref("RTCIdentityProvider")}}</dt> + <dd>Enables a user agent is able to request that an identity assertion be generated or validated.</dd> + <dt>{{domxref("RTCIdentityAssertion")}}</dt> + <dd>Represents the identity of the a remote peer of the current connection. If no peer has yet been set and verified this interface returns <code>null</code>. Once set it can't be changed.</dd> + <dt>{{domxref("RTCIdentityProviderRegistrar")}}</dt> + <dd>Registers an identity provider (idP).</dd> + <dt>{{domxref("RTCIdentityEvent")}}</dt> + <dd>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")}}.</dd> + <dt>{{domxref("RTCIdentityErrorEvent")}}</dt> + <dd>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")}}.</dd> + <dt>{{domxref("RTCCertificate")}}</dt> + <dd>Represents a certificate that an {{domxref("RTCPeerConnection")}} uses to authenticate.</dd> +</dl> + +<h3 id="Telephony">Telephony</h3> + +<p>These interfaces are related to interactivity with public-switched telephone networks (PTSNs).</p> + +<dl> + <dt>{{domxref("RTCDTMFSender")}}</dt> + <dd>Manages the encoding and transmission of dual-tone multi-frequency (DTMF) signaling for an {{domxref("RTCPeerConnection")}}.</dd> + <dt>{{domxref("RTCDTMFToneChangeEvent")}}</dt> + <dd>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).</dd> +</dl> + +<h2 id="Guides">Guides</h2> + +<dl> + <dt><a href="/en-US/docs/Web/API/WebRTC_API/Protocols">Introduction to WebRTC protocols</a></dt> + <dd>This article introduces the protocols on top of which the WebRTC API is built.</dd> + <dt><a href="/en-US/docs/Web/API/WebRTC_API/Connectivity">WebRTC connectivity</a></dt> + <dd>A guide to how WebRTC connections work and how the various protocols and interfaces can be used together to build powerful communication apps.</dd> + <dt><a href="/en-US/docs/Web/API/WebRTC_API/Session_lifetime">Lifetime of a WebRTC session</a></dt> + <dd>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.</dd> + <dt><a href="/en-US/docs/Web/API/WebRTC_API/Signaling_and_video_calling">Signaling and two-way video calling</a></dt> + <dd>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.</dd> + <dt><a href="/en-US/docs/Web/API/WebRTC_API/Using_data_channels">Using WebRTC data channels</a></dt> + <dd>This guide covers how you can use a peer connection and an associated {{domxref("RTCDataChannel")}} to exchange arbitrary data between two peers.</dd> + <dt><a href="/en-US/docs/Web/API/WebRTC_API/Using_DTMF">Using DTMF with WebRTC</a></dt> + <dd>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.</dd> +</dl> + +<h2 id="Tutorials">Tutorials</h2> + +<dl> + <dt><a href="/en-US/docs/Web/API/WebRTC_API/adapter.js">Improving compatibility using WebRTC adapter.js</a></dt> + <dd>The WebRTC organization <a href="https://github.com/webrtc/adapter/">provides on GitHub the WebRTC adapter</a> 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.</dd> + <dt><a href="/en-US/docs/Web/API/WebRTC_API/Taking_still_photos">Taking still photos with WebRTC</a></dt> + <dd>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.</dd> + <dt><a href="/en-US/docs/Web/API/WebRTC_API/Simple_RTCDataChannel_sample">A simple RTCDataChannel sample</a></dt> + <dd>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 <a href="/en-US/docs/Web/API/WebSocket_API">WebSocket API</a>, so that the same programming model can be used for each.</dd> +</dl> + +<h2 id="Resources">Resources</h2> + +<h3 id="Protocols">Protocols</h3> + +<h4 id="WebRTC-proper_protocols">WebRTC-proper protocols</h4> + +<ul> + <li><a href="http://datatracker.ietf.org/doc/draft-ietf-rtcweb-alpn/"><cite>Application Layer Protocol Negotiation for Web Real-Time Communications</cite></a></li> + <li><a href="http://datatracker.ietf.org/doc/draft-ietf-rtcweb-audio/"><cite>WebRTC Audio Codec and Processing Requirements</cite></a></li> + <li><a href="http://datatracker.ietf.org/doc/draft-ietf-rtcweb-data-channel/"><cite>RTCWeb Data Channels</cite></a></li> + <li><a href="http://datatracker.ietf.org/doc/draft-ietf-rtcweb-data-protocol/"><cite>RTCWeb Data Channel Protocol</cite></a></li> + <li><a href="http://datatracker.ietf.org/doc/draft-ietf-rtcweb-rtp-usage/"><cite>Web Real-Time Communication (WebRTC): Media Transport and Use of RTP</cite></a></li> + <li><a href="http://datatracker.ietf.org/doc/draft-ietf-rtcweb-security-arch/"><cite>WebRTC Security Architecture</cite></a></li> + <li><a href="http://datatracker.ietf.org/doc/draft-ietf-rtcweb-transports/"><cite>Transports for RTCWEB</cite></a></li> +</ul> + +<h4 id="Related_supporting_protocols">Related supporting protocols</h4> + +<ul> + <li><a href="https://tools.ietf.org/html/rfc5245">Interactive Connectivity Establishment (ICE): A Protocol for Network Address Translator (NAT) Traversal for Offer/Answer Protocol</a></li> + <li><a href="https://tools.ietf.org/html/rfc5389"><cite>Session Traversal Utilities for NAT (STUN)</cite></a></li> + <li><a href="https://tools.ietf.org/html/rfc7064"><cite>URI Scheme for the Session Traversal Utilities for NAT (STUN) Protocol</cite></a></li> + <li><a href="https://tools.ietf.org/html/rfc7065"><cite>Traversal Using Relays around NAT (TURN) Uniform Resource Identifiers</cite></a></li> + <li><a href="https://tools.ietf.org/html/rfc3264"><cite>An Offer/Answer Model with Session Description Protocol (SDP)</cite></a></li> + <li><a href="https://datatracker.ietf.org/doc/draft-ietf-tram-turn-third-party-authz/"><cite>Session Traversal Utilities for NAT (STUN) Extension for Third Party Authorization</cite></a></li> +</ul> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('WebRTC 1.0')}}</td> + <td>{{Spec2('WebRTC 1.0')}}</td> + <td>The initial definition of the API of WebRTC.</td> + </tr> + <tr> + <td>{{SpecName('Media Capture')}}</td> + <td>{{Spec2('Media Capture')}}</td> + <td>The initial definition of the object conveying the stream of media content.</td> + </tr> + <tr> + <td>{{SpecName('Media Capture DOM Elements')}}</td> + <td>{{Spec2('Media Capture DOM Elements')}}</td> + <td>The initial definition on how to obtain stream of content from DOM Elements</td> + </tr> + </tbody> +</table> + +<p>In additions to these specifications defining the API needed to use WebRTC, there are several protocols, listed under <a href="#Protocols">resources</a>.</p> + +<h2 class="Related_Topics" id="See_also">See also</h2> + +<ul> + <li>{{domxref("MediaDevices")}}</li> + <li>{{domxref("MediaStreamEvent")}}</li> + <li>{{domxref("MediaStreamConstraints")}}</li> + <li>{{domxref("MediaStreamTrack")}}</li> + <li>{{domxref("MessageEvent")}}</li> + <li>{{domxref("MediaStream")}}</li> + <li><a href="https://hacks.mozilla.org/2015/06/firefox-multistream-and-renegotiation-for-jitsi-videobridge/">Firefox multistream and renegotiation for Jitsi Videobridge</a></li> + <li><a href="https://hacks.mozilla.org/2015/04/peering-through-the-webrtc-fog-with-socketpeer/">Peering Through the WebRTC Fog with SocketPeer</a></li> + <li><a href="https://hacks.mozilla.org/2014/04/inside-the-party-bus-building-a-web-app-with-multiple-live-video-streams-interactive-graphics/">Inside the Party Bus: Building a Web App with Multiple Live Video Streams + Interactive Graphics</a></li> +</ul> 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 +--- +<div>{{ ApiRef() }}</div> + +<p><strong><code>Window.getSelection()</code></strong> adalah metode {{domxref("Selection")}} yang menggambarkan teks yang ditandai oleh pengguna atau posisi sekarang.</p> + +<h2 id="Syntak">Syntak</h2> + +<pre class="syntaxbox"><em>selection</em> = <em>window</em>.getSelection();</pre> + +<h3 id="Hasil_Output">Hasil Output</h3> + +<p>Objek {{domxref("Selection")}}</p> + +<p>Ketika berganti ke string, lebih baik menggunakan string kosong (<strong><code>""</code></strong>) atau menggunakan {{domxref("Selection.toString()")}}, hasil output adalah teks yang dipilih.</p> + +<p>Ketika memanggil sebuah {{htmlelement("iframe")}} ini tidak akan ditampilkan (misalnya <code>display: none</code> telah diatur) Firefox akan menampilkan <code>null</code>, sedangkan browser lain akan menampilkan objek {{domxref("Selection")}} dengan {{domxref("Selection.type")}} yang diatur ke <code>None</code>.</p> + +<h2 id="Contoh">Contoh</h2> + +<pre class="brush:js">function foo() { + var selObj = window.getSelection(); + alert(selObj); + var selRange = selObj.getRangeAt(0); + // do stuff with the range +}</pre> + +<h2 id="Catatan">Catatan</h2> + +<h3 id="Representasi_dari_objek_Selection">Representasi dari objek Selection</h3> + +<p>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.</p> + +<p>Pada contoh berikut, <code>selObj.toString()</code> akan otomatis dipanggil ketika melewati {{domxref("window.alert()")}}. Bagaimanapun, mencoba menggunakan properti atau metode JavaScript <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/String" title="JS/String">String</a> seperti <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/length" title="JS/String.length">length</a></code> atau <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substr" title="JS/String.substr">substr</a></code> 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:</p> + +<pre class="brush:js;gutter:false;">var selectedText = selObj.toString();</pre> + +<ul> + <li><code>selObj</code> adalah objek <code>Selection</code>.</li> + <li><code>selectedText</code> adalah sebuah string (Selected text).</li> +</ul> + +<h3 id="Objek_terhubung">Objek terhubung</h3> + +<p>Kamu bisa memanggil {{domxref("Document.getSelection()")}}, yang mana ini bekerja seperti <code>Window.getSelection()</code>.</p> + +<p>Perlu diingat, bahwa saat ini <code>getSelection()</code> tidak bekerja pada elemen {{htmlelement("textarea")}} and {{htmlelement("input")}} di Firefox. Properti {{domxref("HTMLInputElement.setSelectionRange()")}} atau <code>selectionStart</code> dan <code>selectionEnd</code> yang dapat menangani hal ini.</p> + +<p>Perhatikan juga perbedaan atara <em>selection</em> dan <em>focus</em>. {{domxref("Document.activeElement")}} menampilkan elemen yang sedang difokus.</p> + +<h2 id="Spesifikasi">Spesifikasi</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName("Selection API", "#extensions-to-window-interface", "Window.getSelection()")}}</td> + <td>{{Spec2("Selection API")}}</td> + <td>New spec.</td> + </tr> + <tr> + <td>{{SpecName("HTML Editing", "#dom-window-getselection", "Window.getSelection()")}}</td> + <td>{{Spec2("HTML Editing")}}</td> + <td>Initial definition</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + + + +<p>{{Compat("api.Window.getSelection")}}</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="/en-US/docs/Web/API/Selection_API">Selection API</a></li> + <li>{{domxref("Selection")}}</li> + <li>{{domxref("Range")}}</li> + <li>{{domxref("Document.getSelection()")}}</li> + <li>{{domxref("HTMLInputElement.setSelectionRange()")}}</li> +</ul> 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 +--- +<p>{{APIRef}}</p> + +<p><span class="seoSummary">The <code>window</code> object represents a window containing a DOM document; the <code>document</code> property points to the <a href="/en-US/docs/DOM/document">DOM document</a> loaded in that window.</span> A window for a given document can be obtained using the {{Domxref("document.defaultView")}} property.</p> + +<p>This section provides a brief reference for all of the methods, properties, and events available through the DOM <code>window</code> object. The <code>window</code> object implements the <code>Window</code> interface, which in turn inherits from the <code><a href="http://www.w3.org/TR/DOM-Level-2-Views/views.html#Views-AbstractView">AbstractView</a></code> interface. Some additional global functions, namespaces, objects, interfaces, and constructors, not typically associated with the window, but available on it, are listed in the <a href="/en-US/docs/JavaScript/Reference">JavaScript Reference</a> and <a href="/en-US/docs/Web/API/Document_Object_Model" title="/en-US/docs/Web/API/Document_Object_Model">DOM Reference</a>.</p> + +<p>In a tabbed browser, such as Firefox, each tab contains its own <code>window</code> object (and if you're writing an extension, the browser window itself is a separate window too - see <a href="/en-US/docs/Working_with_windows_in_chrome_code#Content_windows">Working with windows in chrome code</a> for more information). That is, the <code>window</code> 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 <code>window</code> object belongs to. Generally, anything that can't reasonably pertain to a tab pertains to the window instead.</p> + +<p>{{InheritanceDiagram}}</p> + +<h2 id="Properties">Properties</h2> + +<p><em>This interface inherits properties from the {{domxref("EventTarget")}} interface and implements properties from the {{domxref("WindowOrWorkerGlobalScope")}} and {{domxref("WindowEventHandlers")}} mixins.</em></p> + +<p>Note that properties which are objects (e.g.,. for overriding the prototype of built-in elements) are listed in a separate section below.</p> + +<dl> + <dt>{{domxref("Window.applicationCache")}} {{readOnlyInline}} {{gecko_minversion_inline("1.9")}}</dt> + <dd>An {{domxref("OfflineResourceList")}} object providing access to the offline resources for the window.</dd> + <dt>{{domxref("Window.closed")}} {{Non-standard_inline}}{{readOnlyInline}}</dt> + <dd>This property indicates whether the current window is closed or not.</dd> + <dt>{{domxref("Window.console")}} {{ReadOnlyInline}}</dt> + <dd>Returns a reference to the console object which provides access to the browser's debugging console.</dd> + <dt>{{domxref("Window.content")}} and Window._content {{Non-standard_inline}} {{obsolete_inline}}{{ReadOnlyInline}}</dt> + <dd>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.</dd> + <dt>{{domxref("Window.controllers")}}{{non-standard_inline}}{{ReadOnlyInline}}</dt> + <dd>Returns the XUL controller objects for the current chrome window.</dd> + <dt>{{domxref("Window.crypto")}} {{readOnlyInline}}</dt> + <dd>Returns the browser crypto object.</dd> + <dt>{{domxref("Window.defaultStatus")}} {{Obsolete_inline("gecko23")}}</dt> + <dd>Gets/sets the status bar text for the given window.</dd> + <dt>{{domxref("Window.devicePixelRatio")}} {{non-standard_inline}}{{ReadOnlyInline}}</dt> + <dd>Returns the ratio between physical pixels and device independent pixels in the current display.</dd> + <dt>{{domxref("Window.dialogArguments")}} {{Fx_minversion_inline(3)}} {{ReadOnlyInline}}</dt> + <dd>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")}}.</dd> + <dt>{{domxref("Window.directories")}} {{obsolete_inline}}</dt> + <dd>Synonym of {{domxref("window.personalbar")}}</dd> + <dt>{{domxref("Window.document")}} {{ReadOnlyInline}}</dt> + <dd>Returns a reference to the document that the window contains.</dd> + <dt>{{domxref("Window.frameElement")}} {{readOnlyInline}}</dt> + <dd>Returns the element in which the window is embedded, or null if the window is not embedded.</dd> + <dt>{{domxref("Window.frames")}} {{readOnlyInline}}</dt> + <dd>Returns an array of the subframes in the current window.</dd> + <dt>{{domxref("Window.fullScreen")}} {{gecko_minversion_inline("1.9")}}</dt> + <dd>This property indicates whether the window is displayed in full screen or not.</dd> + <dt>{{domxref("Window.globalStorage")}} {{gecko_minversion_inline("1.8.1")}} {{Non-standard_inline}} {{Obsolete_inline("gecko13")}}</dt> + <dd>Unsupported since Gecko 13 (Firefox 13). Use {{domxref("Window.localStorage")}} instead.<br> + Was: Multiple storage objects that are used for storing data across multiple pages.</dd> + <dt>{{domxref("Window.history")}} {{ReadOnlyInline}}</dt> + <dd>Returns a reference to the history object.</dd> + <dt>{{domxref("Window.innerHeight")}} {{readOnlyInline}}</dt> + <dd>Gets the height of the content area of the browser window including, if rendered, the horizontal scrollbar.</dd> + <dt>{{domxref("Window.innerWidth")}} {{readOnlyInline}}</dt> + <dd>Gets the width of the content area of the browser window including, if rendered, the vertical scrollbar.</dd> + <dt>{{domxref("Window.isSecureContext")}} {{readOnlyInline}}</dt> + <dd>Indicates whether a context is capable of using features that require secure contexts.</dd> + <dt>{{domxref("Window.length")}} {{readOnlyInline}}</dt> + <dd>Returns the number of frames in the window. See also {{domxref("window.frames")}}.</dd> + <dt>{{domxref("Window.location")}}</dt> + <dd>Gets/sets the location, or current URL, of the window object.</dd> + <dt>{{domxref("Window.locationbar")}} {{ReadOnlyInline}}</dt> + <dd>Returns the locationbar object, whose visibility can be toggled in the window.</dd> + <dt>{{domxref("Window.localStorage")}} {{readOnlyInline}}{{gecko_minversion_inline("1.9.1")}}</dt> + <dd>Returns a reference to the local storage object used to store data that may only be accessed by the origin that created it.</dd> + <dt>{{domxref("Window.menubar")}} {{ReadOnlyInline}}</dt> + <dd>Returns the menubar object, whose visibility can be toggled in the window.</dd> + <dt>{{domxref("Window.messageManager")}} {{gecko_minversion_inline("2.0")}}</dt> + <dd>Returns the <a href="/en-US/docs/The_message_manager">message manager</a> object for this window.</dd> + <dt>{{domxref("Window.mozAnimationStartTime")}} {{ReadOnlyInline}}{{gecko_minversion_inline("2.0")}} {{Deprecated_inline}}</dt> + <dd>The time in milliseconds since epoch at which the current animation cycle began.</dd> + <dt>{{domxref("Window.mozInnerScreenX")}} {{ReadOnlyInline}}{{non-standard_inline}}{{gecko_minversion_inline("1.9.2")}}</dt> + <dd>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 <code>mozScreenPixelsPerCSSPixel</code> in {{interface("nsIDOMWindowUtils")}} for a conversion factor to adapt to screen pixels if needed.</dd> + <dt>{{domxref("Window.mozInnerScreenY")}} {{ReadOnlyInline}} {{non-standard_inline}}{{gecko_minversion_inline("1.9.2")}}</dt> + <dd>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 <code>mozScreenPixelsPerCSSPixel</code> for a conversion factor to adapt to screen pixels if needed.</dd> + <dt>{{domxref("Window.mozPaintCount")}} {{non-standard_inline}}{{ReadOnlyInline}} {{gecko_minversion_inline("2.0")}}</dt> + <dd>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.</dd> + <dt>{{domxref("Window.name")}}</dt> + <dd>Gets/sets the name of the window.</dd> + <dt>{{domxref("Window.navigator")}} {{readOnlyInline}}</dt> + <dd>Returns a reference to the navigator object.</dd> + <dt>{{domxref("Window.opener")}}</dt> + <dd>Returns a reference to the window that opened this current window.</dd> + <dt>{{domxref("Window.orientation")}}{{non-standard_inline}}{{deprecated_inline}}{{readOnlyInline}}</dt> + <dd>Returns the orientation in degrees (in 90 degree increments) of the viewport relative to the device's natural orientation.</dd> + <dt>{{domxref("Window.outerHeight")}} {{readOnlyInline}}</dt> + <dd>Gets the height of the outside of the browser window.</dd> + <dt>{{domxref("Window.outerWidth")}} {{readOnlyInline}}</dt> + <dd>Gets the width of the outside of the browser window.</dd> + <dt>{{domxref("Window.scrollX","Window.pageXOffset")}} {{readOnlyInline}}</dt> + <dd>An alias for {{domxref("window.scrollX")}}.</dd> + <dt>{{domxref("Window.scrollY","Window.pageYOffset")}}{{readOnlyInline}}</dt> + <dd>An alias for {{domxref("window.scrollY")}}</dd> + <dt>{{domxref("Window.sessionStorage")}} {{readOnlyInline}}</dt> + <dd>Returns a reference to the session storage object used to store data that may only be accessed by the origin that created it.</dd> + <dt>{{domxref("Window.parent")}} {{readOnlyInline}}</dt> + <dd>Returns a reference to the parent of the current window or subframe.</dd> + <dt>{{domxref("Window.performance")}} {{readOnlyInline}}</dt> + <dd>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 <a href="/en-US/docs/Navigation_timing">performance-related</a> data. See also <a href="/en-US/docs/Web/API/Navigation_timing_API/Using_Navigation_Timing">Using Navigation Timing</a> for additional information and examples.</dd> + <dt>{{domxref("Window.personalbar")}} {{readOnlyInline}}</dt> + <dd>Returns the personalbar object, whose visibility can be toggled in the window.</dd> + <dt>{{domxref("Window.pkcs11")}} {{obsolete_inline(29)}}</dt> + <dd>Formerly provided access to install and remove PKCS11 modules.</dd> + <dt>{{domxref("Window.returnValue")}} {{Fx_minversion_inline(3)}}</dt> + <dd>The return value to be returned to the function that called {{domxref("window.showModalDialog()")}} to display the window as a modal dialog.</dd> + <dt>{{domxref("Window.screen")}} {{readOnlyInline}}</dt> + <dd>Returns a reference to the screen object associated with the window.</dd> + + <dt>{{domxref("Window.screenX")}} {{readOnlyInline}}</dt> + <dd>Returns the horizontal distance of the left border of the user's browser from the left side of the screen.</dd> + <dt>{{domxref("Window.screenY")}} {{readOnlyInline}}</dt> + <dd>Returns the vertical distance of the top border of the user's browser from the top side of the screen.</dd> + <dt>{{domxref("Window.scrollbars")}} {{readOnlyInline}}</dt> + <dd>Returns the scrollbars object, whose visibility can be toggled in the window.</dd> + <dt>{{domxref("Window.scrollMaxX")}}{{non-standard_inline}}{{ReadOnlyInline}}</dt> + <dd>The maximum offset that the window can be scrolled to horizontally, that is the document width minus the viewport width.</dd> + <dt>{{domxref("Window.scrollMaxY")}}{{non-standard_inline}}{{ReadOnlyInline}}</dt> + <dd>The maximum offset that the window can be scrolled to vertically (i.e., the document height minus the viewport height).</dd> + <dt>{{domxref("Window.scrollX")}} {{readOnlyInline}}</dt> + <dd>Returns the number of pixels that the document has already been scrolled horizontally.</dd> + <dt>{{domxref("Window.scrollY")}} {{readOnlyInline}}</dt> + <dd>Returns the number of pixels that the document has already been scrolled vertically.</dd> + <dt>{{domxref("Window.self")}} {{ReadOnlyInline}}</dt> + <dd>Returns an object reference to the window object itself.</dd> + <dt>{{domxref("Window.sessionStorage")}} {{Fx_minversion_inline("2.0")}}</dt> + <dd>Returns a storage object for storing data within a single page session.</dd> + <dt>{{domxref("Window.sidebar")}} {{non-standard_inline}}{{ReadOnlyInline}}</dt> + <dd>Returns a reference to the window object of the sidebar.</dd> + <dt>{{domxref("Window.speechSynthesis")}} {{ReadOnlyInline}}</dt> + <dd>Returns a {{domxref("SpeechSynthesis")}} object, which is the entry point into using <a href="/en-US/docs/Web/API/Web_Speech_API">Web Speech API</a> speech synthesis functionality.</dd> + <dt>{{domxref("Window.status")}}</dt> + <dd>Gets/sets the text in the statusbar at the bottom of the browser.</dd> + <dt>{{domxref("Window.statusbar")}} {{readOnlyInline}}</dt> + <dd>Returns the statusbar object, whose visibility can be toggled in the window.</dd> + <dt>{{domxref("Window.toolbar")}} {{readOnlyInline}}</dt> + <dd>Returns the toolbar object, whose visibility can be toggled in the window.</dd> + <dt>{{domxref("Window.top")}} {{readOnlyInline}}</dt> + <dd>Returns a reference to the topmost window in the window hierarchy. This property is read only.</dd> + <dt>{{domxref("Window.visualViewport")}} {{readOnlyInline}}</dt> + <dd>Returns a {{domxref("VisualViewport")}} object which represents the visual viewport for a given window.</dd> + <dt>{{domxref("Window.window")}} {{ReadOnlyInline}}</dt> + <dd>Returns a reference to the current window.</dd> + <dt><code>window[0]</code>,<code> window[1]</code>, etc.</dt> + <dd>Returns a reference to the <code>window</code> object in the frames. See {{domxref("Window.frames")}} for more details.</dd> +</dl> + +<h3 id="Properties_implemented_from_elsewhere">Properties implemented from elsewhere</h3> + +<dl> + <dt>{{domxref("WindowOrWorkerGlobalScope.caches")}} {{readOnlyinline}}</dt> + <dd>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.</dd> + <dt>{{domxref("WindowOrWorkerGlobalScope.indexedDB")}} {{readonlyInline}}</dt> + <dd>Provides a mechanism for applications to asynchronously access capabilities of indexed databases; returns an {{domxref("IDBFactory")}} object.</dd> + <dt>{{domxref("WindowOrWorkerGlobalScope.isSecureContext")}} {{readOnlyinline}}</dt> + <dd>Returns a boolean indicating whether the current context is secure (<code>true</code>) or not (<code>false</code>).</dd> + <dt>{{domxref("WindowOrWorkerGlobalScope.origin")}} {{readOnlyinline}}</dt> + <dd>Returns the global object's origin, serialized as a string. (This does not yet appear to be implemented in any browser.)</dd> +</dl> + +<h2 id="Methods">Methods</h2> + +<p><em>This interface inherits methods from the {{domxref("EventTarget")}} interface and implements methods from {{domxref("WindowOrWorkerGlobalScope")}} and {{domxref("EventTarget")}}.</em></p> + +<dl> + <dt>{{domxref("Window.alert()")}}</dt> + <dd>Displays an alert dialog.</dd> + + <dt>{{domxref("Window.back()")}} {{Non-standard_inline}} {{obsolete_inline}}</dt> + <dd>Moves back one in the window history.</dd> + <dt>{{domxref("Window.blur()")}}</dt> + <dd>Sets focus away from the window.</dd> + <dt>{{domxref("Window.cancelAnimationFrame()")}} {{experimental_inline}}</dt> + <dd>Enables you to cancel a callback previously scheduled with {{domxref("Window.requestAnimationFrame")}}.</dd> + <dt>{{domxref("Window.cancelIdleCallback()")}} {{experimental_inline}}</dt> + <dd>Enables you to cancel a callback previously scheduled with {{domxref("Window.requestIdleCallback")}}.</dd> + <dt>{{domxref("Window.captureEvents()")}} {{Deprecated_inline}}</dt> + <dd>Registers the window to capture all events of the specified type.</dd> + <dt>{{domxref("Window.clearImmediate()")}}</dt> + <dd>Cancels the repeated execution set using <code>setImmediate</code>.</dd> + <dt>{{domxref("Window.close()")}}</dt> + <dd>Closes the current window.</dd> + <dt>{{domxref("Window.confirm()")}}</dt> + <dd>Displays a dialog with a message that the user needs to respond to.</dd> + <dt>{{domxref("Window.disableExternalCapture()")}} {{obsolete_inline(24)}}</dt> + <dd>{{todo("NeedsContents")}}</dd> + <dt>{{domxref("Window.dispatchEvent()")}}</dt> + <dd>Used to trigger an event.</dd> + <dt>{{domxref("Window.dump()")}} {{Non-standard_inline}}</dt> + <dd>Writes a message to the console.</dd> + <dt>{{domxref("Window.enableExternalCapture()")}} {{obsolete_inline(24)}}</dt> + <dd>{{todo("NeedsContents")}}</dd> + <dt>{{domxref("Window.find()")}}</dt> + <dd>Searches for a given string in a window.</dd> + <dt>{{domxref("Window.focus()")}}</dt> + <dd>Sets focus on the current window.</dd> + <dt>{{domxref("Window.forward()")}} {{Non-standard_inline}} {{obsolete_inline}}</dt> + <dd>Moves the window one document forward in the history.</dd> + <dt>{{domxref("Window.getAttention()")}} {{Non-standard_inline}} {{obsolete_inline}}</dt> + <dd>Flashes the application icon.</dd> + <dt>{{domxref("Window.getAttentionWithCycleCount()")}}</dt> + <dd>{{todo("NeedsContents")}}</dd> + <dt>{{domxref("Window.getComputedStyle()")}}</dt> + <dd>Gets computed style for the specified element. Computed style indicates the computed values of all CSS properties of the element.</dd> + <dt>{{domxref("Window.getDefaultComputedStyle()")}} {{Non-standard_inline}}</dt> + <dd>Gets default computed style for the specified element, ignoring author stylesheets.</dd> + <dt>{{domxref("Window.getSelection()")}}</dt> + <dd>Returns the selection object representing the selected item(s).</dd> + <dt>{{domxref("Window.home()")}} {{Non-standard_inline}} {{obsolete_inline}}</dt> + <dd>Returns the browser to the home page.</dd> + <dt>{{domxref("Window.matchMedia()")}} {{gecko_minversion_inline("6.0")}}</dt> + <dd>Returns a {{domxref("MediaQueryList")}} object representing the specified media query string.</dd> + <dt>{{domxref("Window.maximize()")}}</dt> + <dd>{{todo("NeedsContents")}}</dd> + <dt>{{domxref("Window.minimize()")}} (top-level XUL windows only)</dt> + <dd>Minimizes the window.</dd> + <dt>{{domxref("Window.moveBy()")}}</dt> + <dd>Moves the current window by a specified amount.</dd> + <dt>{{domxref("Window.moveTo()")}}</dt> + <dd>Moves the window to the specified coordinates.</dd> + <dt>{{domxref("Window.open()")}}</dt> + <dd>Opens a new window.</dd> + <dt>{{domxref("Window.openDialog()")}} {{Non-standard_inline}} {{obsolete_inline}}</dt> + <dd>Opens a new dialog window.</dd> + <dt>{{domxref("Window.postMessage()")}} {{Fx_minversion_inline(3)}}</dt> + <dd>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.</dd> + <dt>{{domxref("Window.print()")}}</dt> + <dd>Opens the Print Dialog to print the current document.</dd> + <dt>{{domxref("Window.prompt()")}}</dt> + <dd>Returns the text entered by the user in a prompt dialog.</dd> + <dt>{{domxref("Window.releaseEvents()")}} {{Non-standard_inline}} {{Deprecated_inline}}</dt> + <dd>Releases the window from trapping events of a specific type.</dd> + <dt>{{domxref("Window.requestAnimationFrame()")}} {{gecko_minversion_inline("2.0")}}</dt> + <dd>Tells the browser that an animation is in progress, requesting that the browser schedule a repaint of the window for the next animation frame.</dd> + <dt>{{domxref("Window.requestIdleCallback()")}} {{experimental_inline}}</dt> + <dd>Enables the scheduling of tasks during a browser's idle periods.</dd> + <dt>{{domxref("Window.resizeBy()")}}</dt> + <dd>Resizes the current window by a certain amount.</dd> + <dt>{{domxref("Window.resizeTo()")}}</dt> + <dd>Dynamically resizes window.</dd> + <dt>{{domxref("Window.restore()")}} {{Non-standard_inline}} {{obsolete_inline}}</dt> + <dd>{{todo("NeedsContents")}}</dd> + <dt>{{domxref("Window.routeEvent()")}} {{obsolete_inline(24)}}</dt> + <dd>{{todo("NeedsContents")}}</dd> + <dt>{{domxref("Window.scroll()")}}</dt> + <dd>Scrolls the window to a particular place in the document.</dd> + <dt>{{domxref("Window.scrollBy()")}}</dt> + <dd>Scrolls the document in the window by the given amount.</dd> + <dt>{{domxref("Window.scrollByLines()")}} {{Non-standard_inline}}</dt> + <dd>Scrolls the document by the given number of lines.</dd> + <dt>{{domxref("Window.scrollByPages()")}} {{Non-standard_inline}}</dt> + <dd>Scrolls the current document by the specified number of pages.</dd> + <dt>{{domxref("Window.scrollTo()")}}</dt> + <dd>Scrolls to a particular set of coordinates in the document.</dd> + <dt>{{domxref("Window.setCursor()")}} {{Non-standard_inline}} (top-level XUL windows only)</dt> + <dd>Changes the cursor for the current window</dd> + <dt>{{domxref("Window.setImmediate()")}}</dt> + <dd>Executes a function after the browser has finished other heavy tasks</dd> + <dt>{{domxref("Window.setResizable()")}} {{Non-standard_inline}}</dt> + <dd>Toggles a user's ability to resize a window.</dd> + <dt>{{domxref("Window.sizeToContent()")}} {{Non-standard_inline}}</dt> + <dd>Sizes the window according to its content.</dd> + <dt>{{domxref("Window.stop()")}}</dt> + <dd>This method stops window loading.</dd> + <dt>{{domxref("Window.updateCommands()")}} {{Non-standard_inline}}</dt> + <dd>Updates the state of commands of the current chrome window (UI).</dd> +</dl> + +<h3 id="Methods_implemented_from_elsewhere">Methods implemented from elsewhere</h3> + +<dl> + <dt>{{domxref("EventTarget.addEventListener()")}}</dt> + <dd>Register an event handler to a specific event type on the window.</dd> + <dt>{{domxref("WindowOrWorkerGlobalScope.atob()")}}</dt> + <dd>Decodes a string of data which has been encoded using base-64 encoding.</dd> + <dt>{{domxref("WindowOrWorkerGlobalScope.btoa()")}}</dt> + <dd>Creates a base-64 encoded ASCII string from a string of binary data.</dd> + <dt>{{domxref("WindowOrWorkerGlobalScope.clearInterval()")}}</dt> + <dd>Cancels the repeated execution set using {{domxref("WindowOrWorkerGlobalScope.setInterval()")}}.</dd> + <dt>{{domxref("WindowOrWorkerGlobalScope.clearTimeout()")}}</dt> + <dd>Cancels the delayed execution set using {{domxref("WindowOrWorkerGlobalScope.setTimeout()")}}.</dd> + <dt>{{domxref("WindowOrWorkerGlobalScope.createImageBitmap()")}}</dt> + <dd>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 <em>(sx, sy)</em> with width sw, and height sh.</dd> + <dt>{{domxref("WindowOrWorkerGlobalScope.fetch()")}}</dt> + <dd>Starts the process of fetching a resource from the network.</dd> + <dt>{{domxref("EventTarget.removeEventListener")}}</dt> + <dd>Removes an event listener from the window.</dd> + <dt>{{domxref("WindowOrWorkerGlobalScope.setInterval()")}}</dt> + <dd>Schedules a function to execute every time a given number of milliseconds elapses.</dd> + <dt>{{domxref("WindowOrWorkerGlobalScope.setTimeout()")}}</dt> + <dd>Schedules a function to execute in a given amount of time.</dd> +</dl> + +<h3 id="Obsolete_methods">Obsolete methods</h3> + +<dl> + <dt>{{domxref("Window.showModalDialog()")}} {{obsolete_inline}}</dt> + <dd>Displays a modal dialog. <strong>This method was removed completely in Chrome 43, and Firefox 55.</strong></dd> +</dl> + +<h2 id="Event_handlers">Event handlers</h2> + +<p>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.</p> + +<p><em>This interface inherits event handlers from the {{domxref("EventTarget")}} interface and implements event handlers from {{domxref("WindowEventHandlers")}}.</em></p> + +<div class="note"> +<p><strong>Note:</strong> Starting in {{Gecko("9.0")}}, you can now use the syntax <code>if ("onabort" in window)</code> 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 <a href="/en-US/docs/DOM/DOM_event_handlers">DOM event handlers</a> for details.</p> +</div> + +<dl> + <dt>{{domxref("GlobalEventHandlers.onabort")}}</dt> + <dd>Called when the loading of a resource has been aborted, such as by a user canceling the load while it is still in progress</dd> + <dt>{{domxref("WindowEventHandlers.onafterprint")}}</dt> + <dd>Called when the print dialog box is closed. See {{event("afterprint")}} event.</dd> + <dt>{{domxref("WindowEventHandlers.onbeforeprint")}}</dt> + <dd>Called when the print dialog box is opened. See {{event("beforeprint")}} event.</dd> + <dt>{{domxref("Window.onbeforeinstallprompt")}}</dt> + <dd>An event handler property dispatched before a user is prompted to save a web site to a home screen on mobile.</dd> + <dt>{{domxref("WindowEventHandlers.onbeforeunload")}}</dt> + <dd>An event handler property for before-unload events on the window.</dd> + <dt>{{domxref("GlobalEventHandlers.onblur")}}</dt> + <dd>Called after the window loses focus, such as due to a popup.</dd> + <dt>{{domxref("GlobalEventHandlers.onchange")}}</dt> + <dd>An event handler property for change events on the window.</dd> + <dt>{{domxref("GlobalEventHandlers.onclick")}}</dt> + <dd>Called after the ANY mouse button is pressed & released</dd> + <dt>{{domxref("GlobalEventHandlers.ondblclick")}}</dt> + <dd>Called when a double click is made with ANY mouse button.</dd> + <dt>{{domxref("GlobalEventHandlers.onclose")}}</dt> + <dd>Called after the window is closed</dd> + <dt>{{domxref("GlobalEventHandlers.oncontextmenu")}}</dt> + <dd>Called when the RIGHT mouse button is pressed</dd> + <dt>{{domxref("Window.ondevicelight")}}</dt> + <dd>An event handler property for any ambient light levels changes</dd> + <dt>{{domxref("Window.ondevicemotion")}} {{gecko_minversion_inline("6.0")}}</dt> + <dd>Called if accelerometer detects a change (For mobile devices)</dd> + <dt>{{domxref("Window.ondeviceorientation")}} {{gecko_minversion_inline("6.0")}}</dt> + <dd>Called when the orientation is changed (For mobile devices)</dd> + <dt>{{domxref("Window.ondeviceorientationabsolute")}} {{non-standard_inline}} Chrome only</dt> + <dd>An event handler property for any device orientation changes.</dd> + <dt>{{domxref("Window.ondeviceproximity")}}</dt> + <dd>An event handler property for device proximity event</dd> + <dt>{{domxref("GlobalEventHandlers.onerror")}}</dt> + <dd>Called when a resource fails to load OR when an error occurs at runtime. See {{event("error")}} event.</dd> + <dt>{{domxref("GlobalEventHandlers.onfocus")}}</dt> + <dd>Called after the window receives or regains focus. See {{event("focus")}} events.</dd> + <dt>{{domxref("WindowEventHandlers.onhashchange")}} {{gecko_minversion_inline("1.9.2")}}</dt> + <dd>An event handler property for {{event('hashchange')}} events on the window; called when the part of the URL after the hash mark ("#") changes.</dd> + <dt>{{domxref("Window.onappinstalled")}}</dt> + <dd>Called when the page is installed as a webapp. See {{event('appinstalled')}} event.</dd> + <dt>{{domxref("Window.ongamepadconnected")}}</dt> + <dd>Represents an event handler that will run when a gamepad is connected (when the {{event('gamepadconnected')}} event fires).</dd> + <dt>{{domxref("Window.ongamepaddisconnected")}}</dt> + <dd>Represents an event handler that will run when a gamepad is disconnected (when the {{event('gamepaddisconnected')}} event fires).</dd> + <dt>{{domxref("Window.oninput")}}</dt> + <dd>Called when the value of an <input> element changes</dd> + <dt>{{domxref("GlobalEventHandlers.onkeydown")}}</dt> + <dd>Called when you begin pressing ANY key. See {{event("keydown")}} event.</dd> + <dt>{{domxref("GlobalEventHandlers.onkeypress")}}</dt> + <dd>Called when a key (except Shift, Fn, and CapsLock) is in pressed position. See {{event("keypress")}} event.</dd> + <dt>{{domxref("GlobalEventHandlers.onkeyup")}}</dt> + <dd>Called when you finish releasing ANY key. See {{event("keyup")}} event.</dd> + <dt>{{domxref("WindowEventHandlers.onlanguagechange")}}</dt> + <dd>An event handler property for {{event("languagechange")}} events on the window.</dd> + <dt>{{domxref("GlobalEventHandlers.onload")}}</dt> + <dd>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.</dd> + <dt>{{domxref("WindowEventHandlers.onmessage")}}</dt> + <dd>Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("message")}} event is raised.</dd> + <dt>{{domxref("GlobalEventHandlers.onmousedown")}}</dt> + <dd>Called when ANY mouse button is pressed.</dd> + <dt>{{domxref("GlobalEventHandlers.onmousemove")}}</dt> + <dd>Called continously when the mouse is moved inside the window.</dd> + <dt>{{domxref("GlobalEventHandlers.onmouseout")}}</dt> + <dd>Called when the pointer leaves the window.</dd> + <dt>{{domxref("GlobalEventHandlers.onmouseover")}}</dt> + <dd>Called when the pointer enters the window</dd> + <dt>{{domxref("GlobalEventHandlers.onmouseup")}}</dt> + <dd>Called when ANY mouse button is released</dd> + <dt>{{domxref("Window.onmozbeforepaint")}} {{gecko_minversion_inline("2.0")}}</dt> + <dd>An event handler property for the <code>MozBeforePaint</code> event, which is sent before repainting the window if the event has been requested by a call to the {{domxref("Window.mozRequestAnimationFrame()")}} method.</dd> + <dt>{{domxref("WindowEventHandlers.onoffline")}}</dt> + <dd>Called when network connection is lost. See {{event("offline")}} event.</dd> + <dt>{{domxref("WindowEventHandlers.ononline")}}</dt> + <dd>Called when network connection is established. See {{event("online")}} event.</dd> + <dt>{{domxref("WindowEventHandlers.onpagehide")}}</dt> + <dd>Called when the user navigates away from the page, before the onunload event. See {{event("pagehide")}} event.</dd> + <dt>{{domxref("WindowEventHandlers.onpageshow")}}</dt> + <dd>Called after all resources and the DOM are fully loaded. See {{event("pageshow")}} event.</dd> + <dt>{{domxref("Window.onpaint")}}</dt> + <dd>An event handler property for paint events on the window.</dd> + <dt>{{domxref("WindowEventHandlers.onpopstate")}} {{gecko_minversion_inline("2.0")}}</dt> + <dd>Called when a back putton is pressed.</dd> + <dt>{{domxref("Window.onrejectionhandled")}} {{experimental_inline}}</dt> + <dd>An event handler for handled {{jsxref("Promise")}} rejection events.</dd> + <dt>{{domxref("GlobalEventHandlers.onreset")}}</dt> + <dd>Called when a form is reset</dd> + <dt>{{domxref("GlobalEventHandlers.onresize")}}</dt> + <dd>Called continuously as you are resizing the window.</dd> + <dt>{{domxref("GlobalEventHandlers.onscroll")}}</dt> + <dd>Called when the scroll bar is moved via ANY means. If the resource fully fits in the window, then this event cannot be invoked</dd> + <dt>{{domxref("GlobalEventHandlers.onwheel")}}</dt> + <dd>Called when the mouse wheel is rotated around any axis</dd> + <dt>{{domxref("GlobalEventHandlers.onselect")}}</dt> + <dd>Called after text in an input field is selected</dd> + <dt>{{domxref("GlobalEventHandlers.onselectionchange")}}</dt> + <dd>Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("selectionchange")}} event is raised.</dd> + <dt>{{domxref("WindowEventHandlers.onstorage")}}</dt> + <dd>Called when there is a change in session storage or local storage. See {{event("storage")}} event</dd> + <dt>{{domxref("GlobalEventHandlers.onsubmit")}}</dt> + <dd>Called when a form is submitted</dd> + <dt>{{domxref("WindowEventHandlers.onunhandledrejection")}} {{experimental_inline}}</dt> + <dd>An event handler for unhandled {{jsxref("Promise")}} rejection events.</dd> + <dt>{{domxref("WindowEventHandlers.onunload")}}</dt> + <dd>Called when the user navigates away from the page.</dd> + <dt>{{domxref("Window.onuserproximity")}}</dt> + <dd>An event handler property for user proximity events.</dd> + <dt>{{domxref("Window.onvrdisplayconnect")}}</dt> + <dd>Represents an event handler that will run when a compatible VR device has been connected to the computer (when the {{event("vrdisplayconnected")}} event fires).</dd> + <dt>{{domxref("Window.onvrdisplaydisconnect")}}</dt> + <dd>Represents an event handler that will run when a compatible VR device has been disconnected from the computer (when the {{event("vrdisplaydisconnected")}} event fires).</dd> + <dt>{{domxref("Window.onvrdisplayactivate")}}</dt> + <dd>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.</dd> + <dt>{{domxref("Window.onvrdisplaydeactivate")}}</dt> + <dd>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.</dd> + <dt>{{domxref("Window.onvrdisplayblur")}}</dt> + <dd>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.</dd> + <dt>{{domxref("Window.onvrdisplayfocus")}}</dt> + <dd>Represents an event handler that will run when presentation to a display has resumed after being blurred (when the {{event("vrdisplayfocus")}} event fires).</dd> + <dt>{{domxref("Window.onvrdisplaypresentchange")}}</dt> + <dd>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).</dd> +</dl> + +<h2 id="Constructors">Constructors</h2> + +<p>See also the <a href="/en-US/docs/DOM/DOM_Reference" title="/en-US/docs/DOM/DOM_Reference">DOM Interfaces</a>.</p> + +<dl> + <dt>{{domxref("DOMParser")}}</dt> + <dd><code>DOMParser</code> can parse XML or HTML source stored in a string into a DOM <a href="https://developer.mozilla.org/en-US/docs/DOM/document" title="document">Document</a>. <code>DOMParser</code> is specified in <a href="https://w3c.github.io/DOM-Parsing/" title="http://html5.org/specs/dom-parsing.html">DOM Parsing and Serialization</a>.</dd> + <dt>{{domxref("Window.GeckoActiveXObject")}}</dt> + <dd>{{todo("NeedsContents")}}</dd> + <dt>{{domxref("Image")}}</dt> + <dd>Used for creating an {{domxref("HTMLImageElement")}}.</dd> + <dt>{{domxref("Option")}}</dt> + <dd>Used for creating an {{domxref("HTMLOptionElement")}}</dd> + <dt>{{domxref("Window.QueryInterface")}}</dt> + <dd>{{todo("NeedsContents")}}</dd> + <dt>{{domxref("Window.XMLSerializer")}}</dt> + <dd>{{todo("NeedsContents")}}</dd> + <dt>{{domxref("Worker")}}</dt> + <dd>Used for creating a <a href="/en-US/docs/DOM/Using_web_workers">Web worker</a></dd> + <dt>{{domxref("Window.XPCNativeWrapper")}}</dt> + <dd>{{todo("NeedsContents")}}</dd> + <dt>{{domxref("Window.XPCSafeJSObjectWrapper")}}</dt> + <dd>{{todo("NeedsContents")}}</dd> +</dl> + +<h2 id="Interfaces">Interfaces</h2> + +<p>See <a href="/en-US/docs/DOM/DOM_Reference" title="/en-US/docs/DOM/DOM_Reference">DOM Reference</a></p> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="/en-US/docs/Working_with_windows_in_chrome_code">Working with windows in chrome code</a></li> +</ul> 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 +--- +<div>{{APIRef}}</div> + +<h2 id="Summary">Summary</h2> + +<p><span class="seoSummary">Properti <code>window</code> dalam obyek window mengarah pada obyek window itu sendiri.</span> Jadi ekspresi berikut mengembalikan obyek window yang sama:</p> + +<pre class="syntaxbox">window.window +window.window.window +window.window.window.window + ... +</pre> + +<p>Pada halaman web, obyek window merupakan obyek global. Ini berarti:</p> + +<ol> + <li>variabel global pada skrip adalah properti dari <code>window</code>: + + <pre class="brush:js">var global = {data: 0}; +alert(global === window.global); // displays "true" +</pre> + </li> + <li>kamu dapat mengakses properti bawaan dari window tanpa perlu menulis prefix <code>window.</code>: + <pre class="brush:js">setTimeout("alert('Hi!')", 50); // equivalent to using window.setTimeout. +alert(window === window.window); // displays "true" +</pre> + </li> +</ol> + +<p>Tujuan adanya properti <code>window</code> yang mengarah pada obyek itu sendiri adalah mempermudah dalam mengarah pada obyek global. Jika tidak, kamu harus melakukannya secara manual <code>var window = this;</code> dibagian awal skrip.</p> + +<p>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/')".</p> + +<h2 id="Spesifikasi">Spesifikasi</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('HTML WHATWG', '#dom-window', 'Window.window')}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td>No difference from the latest snapshot {{SpecName("HTML5.1")}}</td> + </tr> + <tr> + <td>{{SpecName('HTML5.1', 'browsers.html#dom-window', 'Window.window')}}</td> + <td>{{Spec2('HTML5.1')}}</td> + <td>No difference from the {{SpecName("HTML5 W3C")}}</td> + </tr> + <tr> + <td>{{SpecName('HTML5 W3C', 'browsers.html#dom-window', 'Window.window')}}</td> + <td>{{Spec2('HTML5 W3C')}}</td> + <td>First snapshot containing the definition of <code>Window.window</code>.</td> + </tr> + </tbody> +</table> 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 +--- +<div>{{DefaultAPISidebar("XMLHttpRequest")}}</div> + +<p><span class="seoSummary">Use <code>XMLHttpRequest</code> (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.</span> <code>XMLHttpRequest</code> is used heavily in {{Glossary("AJAX")}} programming.</p> + +<p>{{InheritanceDiagram(650, 150)}}</p> + +<p>Despite its name, <code>XMLHttpRequest</code> can be used to retrieve any type of data, not just XML.</p> + +<p>If your communication needs to involve receiving event data or message data from a server, consider using <a href="/en-US/docs/Web/API/Server-sent_events">server-sent events</a> through the {{domxref("EventSource")}} interface. For full-duplex communication, <a href="/en-US/docs/Web/API/WebSockets_API">WebSockets</a> may be a better choice.</p> + +<h2 id="Constructor">Constructor</h2> + +<dl> + <dt>{{domxref("XMLHttpRequest.XMLHttpRequest", "XMLHttpRequest()")}}</dt> + <dd>The constructor initializes an XMLHttpRequest. It must be called before any other method calls.</dd> +</dl> + +<h2 id="Properties">Properties</h2> + +<p><em>This interface also inherits properties of {{domxref("XMLHttpRequestEventTarget")}} and of {{domxref("EventTarget")}}.</em></p> + +<dl> + <dt id="xmlhttprequest-onreadystatechange">{{domxref("XMLHttpRequest.onreadystatechange")}}</dt> + <dd>An {{domxref("EventHandler")}} that is called whenever the <code>readyState</code> attribute changes.</dd> + <dt id="xmlhttprequest-readystate">{{domxref("XMLHttpRequest.readyState")}} {{readonlyinline}}</dt> + <dd>Returns an <code>unsigned short</code>, the state of the request.</dd> + <dt>{{domxref("XMLHttpRequest.response")}} {{readonlyinline}}</dt> + <dd>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.</dd> + <dt id="xmlhttprequest-responsetext">{{domxref("XMLHttpRequest.responseText")}} {{readonlyinline}}</dt> + <dd>Returns a {{domxref("DOMString")}} that contains the response to the request as text, or <code>null</code> if the request was unsuccessful or has not yet been sent.</dd> + <dt id="xmlhttprequest-responsetype">{{domxref("XMLHttpRequest.responseType")}}</dt> + <dd>Is an enumerated value that defines the response type.</dd> + <dt id="xmlhttprequest-responsexml">{{domxref("XMLHttpRequest.responseURL")}} {{readonlyinline}}</dt> + <dd>Returns the serialized URL of the response or the empty string if the URL is null.</dd> + <dt id="xmlhttprequest-responsexml">{{domxref("XMLHttpRequest.responseXML")}} {{readonlyinline}}</dt> + <dd>Returns a {{domxref("Document")}} containing the response to the request, or <code>null</code> if the request was unsuccessful, has not yet been sent, or cannot be parsed as XML or HTML. Not available in workers.</dd> + <dt id="xmlhttprequest-status">{{domxref("XMLHttpRequest.status")}} {{readonlyinline}}</dt> + <dd>Returns an <code>unsigned short</code> with the status of the response of the request.</dd> + <dt id="xmlhttprequest-statustext">{{domxref("XMLHttpRequest.statusText")}} {{readonlyinline}}</dt> + <dd>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 ("<code>200 OK</code>", for example).</dd> +</dl> + +<div class="note"> +<p><strong>Note:</strong> According to the HTTP/2 specification (<a href="https://http2.github.io/http2-spec/#rfc.section.8.1.2.4">8.1.2.4</a> <a href="https://http2.github.io/http2-spec/#HttpResponse">Response Pseudo-Header Fields</a>), HTTP/2 does not define a way to carry the version or reason phrase that is included in an HTTP/1.1 status line.</p> +</div> + +<dl> + <dt id="xmlhttprequest-timeout">{{domxref("XMLHttpRequest.timeout")}}</dt> + <dd>Is an <code>unsigned long</code> representing the number of milliseconds a request can take before automatically being terminated.</dd> + <dt id="xmlhttprequesteventtarget-ontimeout">{{domxref("XMLHttpRequestEventTarget.ontimeout")}}</dt> + <dd>Is an {{domxref("EventHandler")}} that is called whenever the request times out. {{gecko_minversion_inline("12.0")}}</dd> + <dt id="xmlhttprequest-upload">{{domxref("XMLHttpRequest.upload")}} {{readonlyinline}}</dt> + <dd>Is an {{domxref("XMLHttpRequestUpload")}}, representing the upload process.</dd> + <dt id="xmlhttprequest-withcredentials">{{domxref("XMLHttpRequest.withCredentials")}}</dt> + <dd>Is a {{domxref("Boolean")}} that indicates whether or not cross-site <code>Access-Control</code> requests should be made using credentials such as cookies or authorization headers.</dd> +</dl> + +<h3 id="Non-standard_properties">Non-standard properties</h3> + +<dl> + <dt>{{domxref("XMLHttpRequest.channel")}}{{ReadOnlyInline}}</dt> + <dd>Is a {{Interface("nsIChannel")}}. The channel used by the object when performing the request.</dd> + <dt>{{domxref("XMLHttpRequest.mozAnon")}}{{ReadOnlyInline}}</dt> + <dd>Is a boolean. If true, the request will be sent without cookie and authentication headers.</dd> + <dt>{{domxref("XMLHttpRequest.mozSystem")}}{{ReadOnlyInline}}</dt> + <dd>Is a boolean. If true, the same origin policy will not be enforced on the request.</dd> + <dt>{{domxref("XMLHttpRequest.mozBackgroundRequest")}}</dt> + <dd>Is a boolean. It indicates whether or not the object represents a background service request.</dd> + <dt>{{domxref("XMLHttpRequest.mozResponseArrayBuffer")}}{{gecko_minversion_inline("2.0")}} {{obsolete_inline("6")}} {{ReadOnlyInline}}</dt> + <dd>{{jsxref("ArrayBuffer")}}. The response to the request, as a JavaScript typed array.</dd> + <dt>{{domxref("XMLHttpRequest.multipart")}}{{obsolete_inline("22")}}</dt> + <dd><strong>This Gecko-only feature, a boolean, was removed in Firefox/Gecko 22.</strong> Please use <a href="/en-US/docs/Web/API/Server-sent_events">Server-Sent Events</a>, <a href="/en-US/docs/Web/API/WebSockets_API">Web Sockets</a>, or <code>responseText</code> from progress events instead.</dd> +</dl> + +<h3 id="Event_handlers">Event handlers</h3> + +<p><code>onreadystatechange</code> as a property of the <code>XMLHttpRequest</code> instance is supported in all browsers.</p> + +<p>Since then, a number of additional event handlers have been implemented in various browsers (<code>onload</code>, <code>onerror</code>, <code>onprogress</code>, etc.). See <a href="https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest">Using XMLHttpRequest</a>.</p> + +<p>More recent browsers, including Firefox, also support listening to the <code>XMLHttpRequest</code> events via standard {{domxref("EventTarget.addEventListener", "addEventListener()")}} APIs in addition to setting <code>on*</code> properties to a handler function.</p> + +<h2 id="Methods">Methods</h2> + +<dl> + <dt>{{domxref("XMLHttpRequest.abort()")}}</dt> + <dd>Aborts the request if it has already been sent.</dd> + <dt>{{domxref("XMLHttpRequest.getAllResponseHeaders()")}}</dt> + <dd>Returns all the response headers, separated by {{Glossary("CRLF")}}, as a string, or <code>null</code> if no response has been received.</dd> + <dt>{{domxref("XMLHttpRequest.getResponseHeader()")}}</dt> + <dd>Returns the string containing the text of the specified header, or <code>null</code> if either the response has not yet been received or the header doesn't exist in the response.</dd> + <dt>{{domxref("XMLHttpRequest.open()")}}</dt> + <dd>Initializes a request.</dd> + <dt>{{domxref("XMLHttpRequest.overrideMimeType()")}}</dt> + <dd>Overrides the MIME type returned by the server.</dd> + <dt>{{domxref("XMLHttpRequest.send()")}}</dt> + <dd>Sends the request. If the request is asynchronous (which is the default), this method returns as soon as the request is sent.</dd> + <dt>{{domxref("XMLHttpRequest.setRequestHeader()")}}</dt> + <dd>Sets the value of an HTTP request header. You must call <code>setRequestHeader()</code>after <a href="#open"><code>open()</code></a>, but before <code>send()</code>.</dd> +</dl> + +<h3 id="Non-standard_methods">Non-standard methods</h3> + +<dl> + <dt>{{domxref("XMLHttpRequest.init()")}}</dt> + <dd>Initializes the object for use from C++ code.</dd> +</dl> + +<div class="warning"><strong>Warning:</strong> This method must <em>not</em> be called from JavaScript.</div> + +<dl> + <dt>{{domxref("XMLHttpRequest.openRequest()")}}</dt> + <dd>Initializes a request. This method is to be used from native code; to initialize a request from JavaScript code, use <a class="internal" href="/en-US/docs/Mozilla/Tech/XPCOM/Reference/Interface/nsIXMLHttpRequest#open()"><code>open()</code></a> instead. See the documentation for <code>open()</code>.</dd> + <dt>{{domxref("XMLHttpRequest.sendAsBinary()")}}{{deprecated_inline()}}</dt> + <dd>A variant of the <code>send()</code> method that sends binary data.</dd> +</dl> + +<h2 id="Events">Events</h2> + +<dl> + <dt>{{domxref("XMLHttpRequest/abort_event", "abort")}}</dt> + <dd>Fired when a request has been aborted, for example because the program called {{domxref("XMLHttpRequest.abort()")}}.<br> + Also available via the {{domxref("XMLHttpRequestEventTarget/onabort", "onabort")}} property.</dd> + <dt>{{domxref("XMLHttpRequest/error_event", "error")}}</dt> + <dd>Fired when the request encountered an error.<br> + Also available via the {{domxref("XMLHttpRequestEventTarget/onerror", "onerror")}} property.</dd> + <dt>{{domxref("XMLHttpRequest/load_event", "load")}}</dt> + <dd>Fired when an {{domxref("XMLHttpRequest")}} transaction completes successfully.<br> + Also available via the {{domxref("XMLHttpRequestEventTarget/onload", "onload")}} property.</dd> + <dt>{{domxref("XMLHttpRequest/loadend_event", "loadend")}}</dt> + <dd>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")}}).<br> + Also available via the {{domxref("XMLHttpRequestEventTarget/onloadend", "onloadend")}} property.</dd> + <dt>{{domxref("XMLHttpRequest/loadstart_event", "loadstart")}}</dt> + <dd>Fired when a request has started to load data.<br> + Also available via the {{domxref("XMLHttpRequestEventTarget/onloadstart", "onloadstart")}} property.</dd> + <dt>{{domxref("XMLHttpRequest/progress_event", "progress")}}</dt> + <dd>Fired periodically when a request receives more data.<br> + Also available via the {{domxref("XMLHttpRequestEventTarget/onprogress", "onprogress")}} property.</dd> + <dt>{{domxref("XMLHttpRequest/timeout_event", "timeout")}}</dt> + <dd>Fired when progress is terminated due to preset time expiring.<br> + Also available via the {{domxref("XMLHttpRequestEventTarget/ontimeout", "ontimeout")}} property.</dd> +</dl> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('XMLHttpRequest')}}</td> + <td>{{Spec2('XMLHttpRequest')}}</td> + <td>Live standard, latest version</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + + + +<div>{{Compat("api.XMLHttpRequest")}}</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{domxref("XMLSerializer")}}: Serializing a DOM tree into XML</li> + <li>MDN tutorials covering <code>XMLHttpRequest</code>: + <ul> + <li><a href="/en-US/docs/AJAX/Getting_Started">Ajax — Getting Started</a></li> + <li><a href="/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest">Using XMLHttpRequest</a></li> + <li><a href="/en-US/docs/Web/API/XMLHttpRequest/HTML_in_XMLHttpRequest">HTML in XMLHttpRequest</a></li> + <li><a href="/en-US/docs/Web/API/Fetch_API" title="Fetch API">Fetch API</a></li> + </ul> + </li> + <li><a class="external" href="http://www.html5rocks.com/en/tutorials/file/xhr2/">HTML5 Rocks — New Tricks in XMLHttpRequest2</a></li> + <li>Feature-Policy directive {{httpheader("Feature-Policy/sync-xhr", "sync-xhr")}}</li> +</ul> 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 +--- +<div>{{APIRef("XMLHttpRequest")}}</div> + +<div>Dalam panduan ini, kita akan melihat bagaimana cara untuk mengunakan <span class="seoSummary">{{domxref("XMLHttpRequest")}} untuk menyelesaikan permasalahan HTTP request yang dalam penggunaan untuk pertukaran data antara halaman web dan server. Contoh umum dan </span> <span class="tlid-translation translation" lang="id"><span title="">kasus penggunaan lebih jelas untuk XMLHttpRequest disertakan.</span></span></div> + +<div></div> + +<div>Untuk mengirim HTTP request, buatlah sebuah object <code>XMLHttpRequest</code> , buka sebuah URL dan kirim request tersebut. setelah <span class="tlid-translation translation" lang="id"><span title="">transaksi selesai, objek akan berisi informasi yang berguna seperti badan respon dan status HTTP dari hasilnya.</span></span></div> + +<div></div> + +<pre class="brush: js">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();</pre> + +<h2 id="Tipe-Tipe_dari_Request">Tipe-Tipe dari Request</h2> + +<p>Sebuh request yang dihasilkan melalui <code>XMLHttpRequest</code> 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 <code>true</code> atau tidak ditentukan. <code>XMLHttpRequest</code> akan diproses secara asynchronous,jika tidak proses akan berjalan secara synchronous. Diskusi detail dan demonstrasi dari kedua cara merequest tersebut dapat ditemukan pada halaman <a href="/en-US/docs/DOM/XMLHttpRequest/Synchronous_and_Asynchronous_Requests">synchronous and asynchronous requests. </a> <span class="tlid-translation translation" lang="id"><span title="">Jangan gunakan permintaan synchronous di luar Pekerja Web.</span></span></p> + +<div class="note"><strong>Note:</strong> Dimulai dari Gecko 30.0 {{ geckoRelease("30.0") }}, <span class="tlid-translation translation" lang="id"><span title="">permintaan synchronous pada utas utama telah ditinggalkan karena efek negatif terhadap pengalaman pengguna.</span></span></div> + +<div class="note"><strong>Note:</strong> fungsi konstruksi <code>XMLHttpRequest</code> <span class="tlid-translation translation" lang="id"><span title="">tidak terbatas hanya pada dokumen XML.</span> <span title="">Itu dimulai dengan "XML" karena ketika itu dibuat format utama yang awalnya digunakan untuk Asynchronous Data Exchange adalah XML</span></span></div> + +<h2 id="Menangani_Respons">Menangani Respons</h2> + +<p>Ada beberapa jenis <a href="https://xhr.spec.whatwg.org/">atribut respons </a> <span class="tlid-translation translation" lang="id"><span title="">ditentukan oleh spesifikasi standar untuk </span></span>{domxref("XMLHttpRequest.XMLHttpRequest", "XMLHttpRequest()")}} constructor. <span class="tlid-translation translation" lang="id"><span title="">Ini memberi tahu klien membuat informasi penting </span></span><code>XMLHttpRequest</code> <span class="tlid-translation translation" lang="id"><span title=""> tentang status respons.</span> <span title="">Beberapa kasus di mana berurusan dengan jenis respons non-teks mungkin melibatkan beberapa manipulasi dan analisis diuraikan dalam bagian berikut.</span></span></p> + +<h3 id="Menganalisa_dan_Memanipulasi_Properti_responseXML">Menganalisa dan Memanipulasi Properti responseXML</h3> + +<p>Jika kamu mengunakan <code>XMLHttpRequest</code> untuk mendapatkan <span class="tlid-translation translation" lang="id"><span title="">konten dokumen XML jarak jauh,</span></span> properti {{domxref("XMLHttpRequest.responseXML", "responseXML")}} akan menjadi <span class="tlid-translation translation" lang="id"><span title="">objek DOM yang berisi dokumen XML parsing. Ini terbentuk sulit untuk dimanipulasi dan dianalisis. Ada empat cara utama untuk menganalisis dokumen XML ini:</span></span></p> + +<ol> + <li>Menggunakan <a href="/en-US/docs/Web/XPath">XPath</a> <span class="tlid-translation translation" lang="id"><span title="">untuk mengatasi (atau menunjuk ke) bagian-bagiannya.</span></span></li> + <li>Secara manual <a href="/en-US/docs/Web/Guide/Parsing_and_serializing_XML">Parsing dan men-serialisasikan XML</a> ke string atau objek</li> + <li>Menggunakan {{domxref("XMLSerializer")}} untuk meng-serialisasi <strong>Pohon DOM ke strings atau ke file</strong>.</li> + <li>{{jsxref("RegExp")}} bisa digunakan jika kamu selalu tau konten dari XML document sebelumnya. Kamu <span class="tlid-translation translation" lang="id"><span title="">mungkin ingin menghapus jeda baris, jika Anda menggunakan RegEx untuk memindai berkenaan dengan jeda baris.</span> <span title="">Namun, metode ini adalah "pilihan terakhir" karena jika kode XML sedikit berubah, metode ini kemungkinan akan gagal.</span></span></li> +</ol> + +<div class="note"> +<p><strong>Note:</strong> <code>XMLHttpRequest</code> <span class="tlid-translation translation" lang="id"><span title="">sekarang dapat menafsirkan HTML untuk Anda menggunakan</span></span> properti {{domxref("XMLHttpRequest.responseXML", "responseXML")}}. Baca artikel <a href="/en-US/docs/Web/API/XMLHttpRequest/HTML_in_XMLHttpRequest">HTML dalam XMLHttpRequest</a> untuk mempelajari cara untuk melakukannya.</p> +</div> + +<h3 id="Memproses_sebuah_Properti_responseText_yang_Berisi_HTML_Dokument">Memproses sebuah Properti responseText yang Berisi HTML Dokument</h3> + +<p>Jika kamu mengunakan <code>XMLHttpRequest</code> 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</p> + +<p>If you use <code>XMLHttpRequest</code> 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. <span class="tlid-translation translation" lang="id"><span title="">Ada tiga cara utama untuk menganalisis dan mengurai string HTML mentah ini:</span></span></p> + +<ol> + <li>Use the <code>XMLHttpRequest.responseXML</code> property as covered in the article <a href="/en-US/docs/Web/API/XMLHttpRequest/HTML_in_XMLHttpRequest">HTML in XMLHttpRequest</a>.</li> + <li>Inject the content into the body of a <a href="/en-US/docs/Web/API/DocumentFragment">document fragment</a> via <code>fragment.body.innerHTML</code> and traverse the DOM of the fragment.</li> + <li>{{jsxref("RegExp")}} can be used if you always know the content of the HTML <code>responseText</code> 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.</li> +</ol> + +<h2 id="Handling_binary_data">Handling binary data</h2> + +<p>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 <code>XMLHttpRequest</code> into sending binary data. These involve utilizing the {{domxref("XMLHttpRequest.overrideMimeType", "overrideMimeType()")}} method on the <code>XMLHttpRequest</code> object and is a workable solution.</p> + +<pre class="brush:js">var oReq = new XMLHttpRequest(); +oReq.open("GET", url); +// retrieve data unprocessed as a binary string +oReq.overrideMimeType("text/plain; charset=x-user-defined"); +/* ... */ +</pre> + +<p>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.</p> + +<p>For example, consider this snippet, which uses the <code>responseType</code> of <code>"arraybuffer"</code> to fetch the remote content into a {{jsxref("ArrayBuffer")}} object, which stores the raw binary data.</p> + +<pre class="brush:js">var oReq = new XMLHttpRequest(); + +oReq.onload = function(e) { + var arraybuffer = oReq.response; // not responseText + /* ... */ +} +oReq.open("GET", url); +oReq.responseType = "arraybuffer"; +oReq.send();</pre> + +<p>For more examples check out the <a href="/en-US/docs/DOM/XMLHttpRequest/Sending_and_Receiving_Binary_Data">Sending and Receiving Binary Data</a> page</p> + +<h2 id="Monitoring_progress">Monitoring progress</h2> + +<p><code>XMLHttpRequest</code> 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.</p> + +<p>Support for DOM {{event("progress")}} event monitoring of <code>XMLHttpRequest</code> transfers follows the <a href="https://xhr.spec.whatwg.org/#interface-progressevent">specification for progress events</a>: these events implement the {{domxref("ProgressEvent")}} interface. The actual events you can monitor to determine the state of an ongoing transfer are:</p> + +<dl> + <dt>{{event("progress")}}</dt> + <dd>The amount of data that has been retrieved has changed.</dd> + <dt>{{event("load")}}</dt> + <dd>The transfer is complete; all data is now in the <code>response</code></dd> +</dl> + +<pre class="brush:js">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."); +}</pre> + +<p>Lines 3-6 add event listeners for the various events that are sent while performing a data transfer using <code>XMLHttpRequest</code>.</p> + +<div class="note"><strong>Note:</strong> You need to add the event listeners before calling <code>open()</code> on the request. Otherwise the <code>progress</code> events will not fire.</div> + +<p>The progress event handler, specified by the <code>updateProgress()</code> 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 <code>total</code> and <code>loaded</code> fields. However, if the <code>lengthComputable</code> field is false, the total length is not known and will be zero.</p> + +<p>Progress events exist for both download and upload transfers. The download events are fired on the <code>XMLHttpRequest</code> object itself, as shown in the above sample. The upload events are fired on the <code>XMLHttpRequest.upload</code> object, as shown below:</p> + +<pre class="brush:js">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(); +</pre> + +<div class="note"><strong>Note:</strong> Progress events are not available for the <code>file:</code> protocol.</div> + +<div class="note"> +<p><strong>Note:</strong> 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.</p> +</div> + +<div class="note"> +<p><strong>Note:</strong> As of {{Gecko("12.0")}}, if your progress event is called with a <code>responseType</code> of "moz-blob", the value of response is a {{domxref("Blob")}} containing the data received so far.</p> +</div> + +<p>One can also detect all three load-ending conditions (<code>abort</code>, <code>load</code>, or <code>error</code>) using the <code>loadend</code> event:</p> + +<pre class="brush:js">req.addEventListener("loadend", loadEnd); + +function loadEnd(e) { + console.log("The transfer finished (although we don't know if it succeeded or not)."); +} +</pre> + +<p>Note there is no way to be certain, from the information received by the <code>loadend</code> 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.</p> + +<h2 id="Submitting_forms_and_uploading_files">Submitting forms and uploading files</h2> + +<p>Instances of <code>XMLHttpRequest</code> can be used to submit forms in two ways:</p> + +<ul> + <li>using only AJAX</li> + <li>using the {{domxref("XMLHttpRequest.FormData", "FormData")}} API</li> +</ul> + +<p>Using the <code>FormData</code> API is the simplest and fastest, but has the disadvantage that data collected can not be <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify">stringified</a>.<br> + Using only AJAX is more complex, but typically more flexible and powerful.</p> + +<h3 id="Using_nothing_but_XMLHttpRequest">Using nothing but <code>XMLHttpRequest</code></h3> + +<p>Submitting forms without the <code>FormData</code> API does not require other APIs for most use cases. The only case where you need an additional API is <strong>if you want to upload one or more files</strong>, where you use the {{domxref("FileReader")}} API.</p> + +<h4 id="A_brief_introduction_to_the_submit_methods">A brief introduction to the submit methods</h4> + +<p>An html {{ HTMLElement("form") }} can be sent in four ways:</p> + +<ul> + <li>using the <code>POST</code> method and setting the <code>enctype</code> attribute to <code>application/x-www-form-urlencoded</code> (default);</li> + <li>using the <code>POST</code> method and setting the <code>enctype</code> attribute to <code>text/plain</code>;</li> + <li>using the <code>POST</code> method and setting the <code>enctype</code> attribute to <code>multipart/form-data</code>;</li> + <li>using the <code>GET</code> method (in this case the <code>enctype</code> attribute will be ignored).</li> +</ul> + +<p>Now, consider the submission of a form containing only two fields, named <code>foo</code> and <code>baz</code>. If you are using the <code>POST</code> method the server will receive a string similar to one of the following three examples, depending on the encoding type you are using:</p> + +<ul> + <li> + <p>Method: <code>POST</code>; Encoding type: <code>application/x-www-form-urlencoded</code> (default):</p> + + <pre class="brush:plain">Content-Type: application/x-www-form-urlencoded + +foo=bar&baz=The+first+line.%0D%0AThe+second+line.%0D%0A</pre> + </li> + <li> + <p>Method: <code>POST</code>; Encoding type: <code>text/plain</code>:</p> + + <pre class="brush:plain">Content-Type: text/plain + +foo=bar +baz=The first line. +The second line.</pre> + </li> + <li> + <p>Method: <code>POST</code>; Encoding type: <code><a href="/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types#multipartform-data">multipart/form-data</a></code>:</p> + + <pre class="brush:plain">Content-Type: multipart/form-data; boundary=---------------------------314911788813839 + +-----------------------------314911788813839 +Content-Disposition: form-data; name="foo" + +bar +-----------------------------314911788813839 +Content-Disposition: form-data; name="baz" + +The first line. +The second line. + +-----------------------------314911788813839--</pre> + </li> +</ul> + +<p>However, if you are using the <code>GET</code> method, a string like the following will be simply added to the URL:</p> + +<pre class="brush:plain">?foo=bar&baz=The%20first%20line.%0AThe%20second%20line.</pre> + +<h4 id="A_little_vanilla_framework">A little vanilla framework</h4> + +<p>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 <em>everything</em>. Therefore, how to send forms in <em>pure</em> AJAX is too complex to be explained here in detail. For this reason, here we place <strong>a complete (yet didactic) framework</strong>, able to use all four ways to <em>submit</em>, and to <strong>upload files</strong>:</p> + +<div style="height: 400px; margin-bottom: 12px; overflow: auto;"> +<pre class="brush: html"><!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></pre> +</div> + +<p>To test this, create a page named <strong>register.php</strong> (which is the <code>action</code> attribute of these sample forms), and put the following <em>minimalistic</em> content:</p> + +<pre class="brush: php"><?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); + +</pre> + +<p>The syntax to activate this script is simply:</p> + +<pre class="syntaxbox">AJAXSubmit(myForm);</pre> + +<div class="note"><strong>Note:</strong> 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 <strong>an experimental technique</strong>. If you do not need to upload binary files, this framework works fine in most browsers.</div> + +<div class="note"><strong>Note:</strong> 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 <code>FileReader</code> API. But, since the aim of this script is to work with a <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify">stringifiable</a> raw data, we used the {{domxref("XMLHttpRequest.sendAsBinary()", "sendAsBinary()")}} method in conjunction with the {{domxref("FileReader.readAsBinaryString()", "readAsBinaryString()")}} method of the <code>FileReader</code> 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 <code>FormData</code> API.</div> + +<div class="note"><strong>Note:</strong> The non-standard <code>sendAsBinary</code> method is considered deprecated as of Gecko 31 {{geckoRelease(31)}} and will be removed soon. The standard <code>send(Blob data)</code> method can be used instead.</div> + +<h3 id="Using_FormData_objects">Using FormData objects</h3> + +<p>The {{domxref("XMLHttpRequest.FormData", "FormData")}} constructor lets you compile a set of key/value pairs to send using <code>XMLHttpRequest</code>. 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 <code>submit()</code> 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 <code>XMLHttpRequest</code>. For examples, and explanations of how one can utilize FormData with XMLHttpRequests, see the <a href="/en-US/docs/DOM/XMLHttpRequest/FormData/Using_FormData_Objects">Using FormData Objects</a> page. For didactic purposes here is <strong>a <em>translation</em> of <a href="#A_little_vanilla_framework">the previous example</a> transformed to use the <code>FormData</code> API</strong>. Note the brevity of the code:</p> + +<div style="height: 400px; margin-bottom: 12px; overflow: auto;"> +<pre class="brush: html"><!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></pre> +</div> + +<div class="note"><strong>Note:</strong> As we said,<strong> {{domxref("FormData")}} objects are not <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify">stringifiable</a> objects</strong>. If you want to stringify a submitted data, use <a href="#A_little_vanilla_framework">the previous <em>pure</em>-AJAX example</a>. Note also that, although in this example there are some <code>file</code> {{ HTMLElement("input") }} fields, <strong>when you submit a form through the <code>FormData</code> API you do not need to use the {{domxref("FileReader")}} API also</strong>: files are automatically loaded and uploaded.</div> + +<h2 id="Get_last_modified_date">Get last modified date</h2> + +<pre class="brush: js">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();</pre> + +<h3 id="Do_something_when_last_modified_date_changes">Do something when last modified date changes</h3> + +<p>Let's create two functions:</p> + +<pre class="brush: js">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(); +}</pre> + +<p>And to test:</p> + +<pre class="brush: js">/* 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() + "!"); +});</pre> + +<p>If you want to know <strong><em>if</em> <em>the current page</em> has changed</strong>, please read the article about {{domxref("document.lastModified")}}.</p> + +<h2 id="Cross-site_XMLHttpRequest">Cross-site XMLHttpRequest</h2> + +<p>Modern browsers support cross-site requests by implementing the <a href="/en-US/docs/Web/HTTP/CORS">Cross-Origin Resource Sharing</a> (CORS) standard. As long as the server is configured to allow requests from your web application's origin, <code>XMLHttpRequest</code> will work. Otherwise, an <code>INVALID_ACCESS_ERR</code> exception is thrown.</p> + +<h2 id="Bypassing_the_cache">Bypassing the cache</h2> + +<p>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:</p> + +<pre class="brush:plain">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 +</pre> + +<p>As the local cache is indexed by URL, this causes every request to be unique, thereby bypassing the cache.</p> + +<p>You can automatically adjust URLs using the following code:</p> + +<pre class="brush:js">var oReq = new XMLHttpRequest(); + +oReq.open("GET", url + ((/\?/).test(url) ? "&" : "?") + (new Date()).getTime()); +oReq.send(null);</pre> + +<h2 id="Security">Security</h2> + +<p>{{fx_minversion_note(3, "Versions of Firefox prior to Firefox 3 allowed you to set the preference <code>capability.policy.<policyname>.XMLHttpRequest.open</policyname></code> to <code>allAccess</code> to give specific sites cross-site access. This is no longer supported.")}}</p> + +<p>{{fx_minversion_note(5, "Versions of Firefox prior to Firefox 5 could use <code>netscape.security.PrivilegeManager.enablePrivilege(\"UniversalBrowserRead\");</code> to request cross-site access. This is no longer supported, even though it produces no warning and permission dialog is still presented.")}}</p> + +<p>The recommended way to enable cross-site scripting is to use the <code>Access-Control-Allow-Origin</code> HTTP header in the response to the XMLHttpRequest.</p> + +<h3 id="XMLHttpRequests_being_stopped">XMLHttpRequests being stopped</h3> + +<p>If you conclude with an XMLHttpRequest receiving <code>status=0</code> and <code>statusText=null</code>, this means the request was not allowed to be performed. It was <code><a href="https://xhr.spec.whatwg.org/#dom-xmlhttprequest-unsent">UNSENT</a></code>. A likely cause for this is when the <a href="https://www.w3.org/TR/2010/CR-XMLHttpRequest-20100803/#xmlhttprequest-origin"><code>XMLHttpRequest</code> origin</a> (at the creation of the XMLHttpRequest) has changed when the XMLHttpRequest is subsequently <code>open()</code>. 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, <code>open()</code>) 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.</p> + +<h2 id="Workers">Workers</h2> + +<p>Setting <code>overrideMimeType</code> does not work from a {{domxref("Worker")}}. See {{bug(678057)}} for more details. Other browsers may handle this differently.</p> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('XMLHttpRequest')}}</td> + <td>{{Spec2('XMLHttpRequest')}}</td> + <td>Live standard, latest version</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("api.XMLHttpRequest")}}</p> + +<h2 id="See_also">See also</h2> + +<ol> + <li><a href="/en-US/docs/AJAX/Getting_Started">MDN AJAX introduction</a></li> + <li><a href="/en-US/docs/Web/API/XMLHttpRequest/HTML_in_XMLHttpRequest">HTML in XMLHttpRequest</a></li> + <li><a href="/en-US/docs/Web/HTTP/Access_control_CORS">HTTP access control</a></li> + <li><a href="/en-US/docs/How_to_check_the_security_state_of_an_XMLHTTPRequest_over_SSL">How to check the security state of an XMLHTTPRequest over SSL</a></li> + <li><a href="http://www.peej.co.uk/articles/rich-user-experience.html">XMLHttpRequest - REST and the Rich User Experience</a></li> + <li><a href="https://msdn.microsoft.com/library/ms535874">Microsoft documentation</a></li> + <li><a href="http://jibbering.com/2002/4/httprequest.html">"Using the XMLHttpRequest Object" (jibbering.com)</a></li> + <li><a href="https://xhr.spec.whatwg.org/">The <code>XMLHttpRequest</code> object: WHATWG specification</a></li> +</ol> |