From 218934fa2ed1c702a6d3923d2aa2cc6b43c48684 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:43:23 -0500 Subject: initial commit --- .../api/audiocontext/createoscillator/index.html | 118 ++++ files/vi/web/api/audiocontext/index.html | 305 +++++++++ files/vi/web/api/canvas_api/index.html | 129 ++++ files/vi/web/api/childnode/index.html | 78 +++ files/vi/web/api/childnode/remove/index.html | 97 +++ files/vi/web/api/document_object_model/index.html | 387 +++++++++++ .../document_object_model/introduction/index.html | 223 +++++++ files/vi/web/api/eventsource/index.html | 127 ++++ files/vi/web/api/eventsource/url/index.html | 59 ++ files/vi/web/api/fetch_api/index.html | 100 +++ files/vi/web/api/file/index.html | 99 +++ files/vi/web/api/geolocation_api/index.html | 244 +++++++ .../api/htmlcanvaselement/getcontext/index.html | 140 ++++ files/vi/web/api/htmlcanvaselement/index.html | 114 ++++ files/vi/web/api/htmlelement/dataset/index.html | 139 ++++ files/vi/web/api/htmlelement/index.html | 268 ++++++++ files/vi/web/api/htmlformelement/index.html | 246 +++++++ files/vi/web/api/htmlformelement/reset/index.html | 28 + files/vi/web/api/index.html | 34 + files/vi/web/api/navigator/geolocation/index.html | 53 ++ files/vi/web/api/navigator/index.html | 186 ++++++ .../vi/web/api/navigator/sendbeacon-vi/index.html | 104 +++ files/vi/web/api/node/index.html | 373 +++++++++++ files/vi/web/api/node/insertbefore/index.html | 166 +++++ files/vi/web/api/node/parentelement/index.html | 50 ++ files/vi/web/api/node/parentnode/index.html | 63 ++ files/vi/web/api/notification/index.html | 408 ++++++++++++ files/vi/web/api/touch_events/index.html | 340 ++++++++++ .../index.html | 61 ++ files/vi/web/api/url_api/index.html | 122 ++++ files/vi/web/api/webrtc_api/index.html | 233 +++++++ files/vi/web/api/webrtc_api/protocols/index.html | 57 ++ files/vi/web/api/websockets_api/index.html | 253 +++++++ .../writing_a_websocket_server_in_java/index.html | 217 ++++++ files/vi/web/api/window/index.html | 729 +++++++++++++++++++++ files/vi/web/api/window/prompt/index.html | 86 +++ 36 files changed, 6436 insertions(+) create mode 100644 files/vi/web/api/audiocontext/createoscillator/index.html create mode 100644 files/vi/web/api/audiocontext/index.html create mode 100644 files/vi/web/api/canvas_api/index.html create mode 100644 files/vi/web/api/childnode/index.html create mode 100644 files/vi/web/api/childnode/remove/index.html create mode 100644 files/vi/web/api/document_object_model/index.html create mode 100644 files/vi/web/api/document_object_model/introduction/index.html create mode 100644 files/vi/web/api/eventsource/index.html create mode 100644 files/vi/web/api/eventsource/url/index.html create mode 100644 files/vi/web/api/fetch_api/index.html create mode 100644 files/vi/web/api/file/index.html create mode 100644 files/vi/web/api/geolocation_api/index.html create mode 100644 files/vi/web/api/htmlcanvaselement/getcontext/index.html create mode 100644 files/vi/web/api/htmlcanvaselement/index.html create mode 100644 files/vi/web/api/htmlelement/dataset/index.html create mode 100644 files/vi/web/api/htmlelement/index.html create mode 100644 files/vi/web/api/htmlformelement/index.html create mode 100644 files/vi/web/api/htmlformelement/reset/index.html create mode 100644 files/vi/web/api/index.html create mode 100644 files/vi/web/api/navigator/geolocation/index.html create mode 100644 files/vi/web/api/navigator/index.html create mode 100644 files/vi/web/api/navigator/sendbeacon-vi/index.html create mode 100644 files/vi/web/api/node/index.html create mode 100644 files/vi/web/api/node/insertbefore/index.html create mode 100644 files/vi/web/api/node/parentelement/index.html create mode 100644 files/vi/web/api/node/parentnode/index.html create mode 100644 files/vi/web/api/notification/index.html create mode 100644 files/vi/web/api/touch_events/index.html create mode 100644 files/vi/web/api/touch_events/supporting_both_touchevent_and_mouseevent/index.html create mode 100644 files/vi/web/api/url_api/index.html create mode 100644 files/vi/web/api/webrtc_api/index.html create mode 100644 files/vi/web/api/webrtc_api/protocols/index.html create mode 100644 files/vi/web/api/websockets_api/index.html create mode 100644 files/vi/web/api/websockets_api/writing_a_websocket_server_in_java/index.html create mode 100644 files/vi/web/api/window/index.html create mode 100644 files/vi/web/api/window/prompt/index.html (limited to 'files/vi/web/api') diff --git a/files/vi/web/api/audiocontext/createoscillator/index.html b/files/vi/web/api/audiocontext/createoscillator/index.html new file mode 100644 index 0000000000..e0a786a181 --- /dev/null +++ b/files/vi/web/api/audiocontext/createoscillator/index.html @@ -0,0 +1,118 @@ +--- +title: AudioContext.createOscillator() +slug: Web/API/AudioContext/createOscillator +translation_of: Web/API/BaseAudioContext/createOscillator +--- +

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

+ +
+

Phương thức createOscillator() của giao thức {{ domxref("AudioContext") }} tạo một cái {{ domxref("OscillatorNode") }} (nút máy dao động). Tức là ta cái nguồn từ dạng sóng.

+
+ +

Cú pháp

+ +
var audioCtx = new AudioContext();
+var oscillator = audioCtx.createOscillator();
+ +

Trả về

+ +

Một cái {{domxref("OscillatorNode")}}.

+ +

Ví dụ

+ +

Ví dụ này trình bày sử dụng đơn giản của một cái AudioContext để tạo một cái OsillatorNode. Để biết thêm thông tin, xem biểu hiện, và trang {{domxref("OscillatorNode")}} của chúng tôi

+ +

Ví dụ này trình bày sử dụng đơn giản của một cái AudioContext để tạo một cái OsillatorNode. Để biết thêm thông tin, xem biểu hiện Violent Theremin (app.js); và trang {{ domxref("OscillatorNode") }} của chúng tôi.

+ +
// create web audio api context
+var audioCtx = new (window.AudioContext || window.webkitAudioContext)();
+
+// create Oscillator node
+var oscillator = audioCtx.createOscillator();
+
+oscillator.type = 'square';
+oscillator.frequency.value = 3000; // Hz
+oscillator.connect(audioCtx.destination);
+oscillator.start();
+ +

Quy cách

+ + + + + + + + + + + + + + +
Quy cáchĐịa vịChú thích
{{SpecName('Web Audio API', '#widl-AudioContext-createOscillator-OscillatorNode', 'createOscillator')}}{{Spec2('Web Audio API')}} 
+ +

Tương thích trình duyệt

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + +
Đặc trưngChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(10.0)}}{{property_prefix("webkit")}}{{CompatVersionUnknown}}{{CompatGeckoDesktop(25.0)}} {{CompatNo}}15.0{{property_prefix("webkit")}}
+ 22 (unprefixed)
6.0{{property_prefix("webkit")}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Đặc trưngAndroidEdgeFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatUnknown}}{{CompatVersionUnknown}}26.01.2{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}33.0
+
+ +

Xem thêm

+ + diff --git a/files/vi/web/api/audiocontext/index.html b/files/vi/web/api/audiocontext/index.html new file mode 100644 index 0000000000..da175915e4 --- /dev/null +++ b/files/vi/web/api/audiocontext/index.html @@ -0,0 +1,305 @@ +--- +title: AudioContext +slug: Web/API/AudioContext +tags: + - API + - Audio + - AudioContext + - Interface + - NeedsTranslation + - Reference + - TopicStub + - Web Audio API + - sound +translation_of: Web/API/AudioContext +--- +

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

+ +
+

The AudioContext interface represents an audio-processing graph built from audio modules linked together, each represented by an {{domxref("AudioNode")}}. An audio context controls both the creation of the nodes it contains and the execution of the audio processing, or decoding. You need to create an AudioContext before you do anything else, as everything happens inside a context.

+
+ +

An AudioContext can be a target of events, therefore it implements the {{domxref("EventTarget")}} interface.

+ +

{{InheritanceDiagram}}

+ +

Constructor

+ +
+
{{domxref("AudioContext.AudioContext", "AudioContext()")}}
+
Creates and returns a new AudioContext object.
+
+ +

Properties

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

Event handlers

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

Methods

+ +

Also implements methods from the interface {{domxref("EventTarget")}}.

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

Obsolete methods

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

Examples

+ +

Basic audio context declaration:

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

Cross browser variant:

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

Specifications

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

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(10.0)}}{{property_prefix("webkit")}}
+ 35
{{CompatVersionUnknown}}{{CompatGeckoDesktop(25.0)}} {{CompatNo}}15.0{{property_prefix("webkit")}}
+ 22
6.0{{property_prefix("webkit")}}
createStereoPanner(){{CompatChrome(42.0)}}{{CompatVersionUnknown}}{{CompatGeckoDesktop(37.0)}} {{CompatNo}}{{CompatNo}}{{CompatNo}}
onstatechange, state, suspend(), resume(){{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoDesktop(40.0)}}{{CompatNo}}{{CompatNo}}{{CompatSafari(8.0)}}
createConstantSource(){{CompatChrome(56.0)}}{{CompatNo}}{{CompatGeckoDesktop(52)}}{{CompatNo}}{{CompatOpera(43)}}{{CompatNo}}
Unprefixed{{CompatVersionUnknown}}{{CompatVersionUnknown}}    
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroid WebviewEdgeFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoDesktop(37.0)}} 2.2{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatVersionUnknown}}
createStereoPanner(){{CompatChrome(42.0)}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatChrome(42.0)}}
onstatechange, state, suspend(), resume(){{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatVersionUnknown}}
createConstantSource(){{CompatChrome(56.0)}}{{CompatNo}}{{CompatGeckoMobile(52)}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatChrome(56.0)}}
Unprefixed{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatOperaMobile(43)}}{{CompatUnknown}}{{CompatVersionUnknown}}
+
+ +

See also

+ + diff --git a/files/vi/web/api/canvas_api/index.html b/files/vi/web/api/canvas_api/index.html new file mode 100644 index 0000000000..dc582ea7ce --- /dev/null +++ b/files/vi/web/api/canvas_api/index.html @@ -0,0 +1,129 @@ +--- +title: Canvas API +slug: Web/API/Canvas_API +translation_of: Web/API/Canvas_API +--- +
{{CanvasSidebar}}
+ +

Canvas API cung cấp phương tiện để vẽ đồ họa thông qua JavaScript và HTML {{HtmlElement("canvas")}} thuộc tính. Nó có thể được sử dụng cho hình động, đồ họa game, trực quan hóa dữ liệu, xử lí ảnh và video trong thời gian thực.

+ +

Canvas API tập trung vào đồ họa 2D. WebGL API, nó cũng sử dụng <canvas> , để vẽ đồ họa 2D và 3D.

+ +

Ví dụ đơn giản

+ +

This simple example draws a green rectangle onto a canvas.

+ +

HTML

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

JavaScript

+ +

The {{domxref("Document.getElementById()")}} method gets a reference to the HTML <canvas> element. Next, the {{domxref("HTMLCanvasElement.getContext()")}} method gets that element's context—the thing onto which the drawing will be rendered.

+ +

The actual drawing is done using the {{domxref("CanvasRenderingContext2D")}} interface. The {{domxref("CanvasRenderingContext2D.fillStyle", "fillStyle")}} property makes the rectangle green. The {{domxref("CanvasRenderingContext2D.fillRect()", "fillRect()")}} method places its top-left corner at (10, 10), and gives it a size of 150 units wide by 100 tall.

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

Result

+ +

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

+ +

Reference

+ +
+ +
+ +
+

Note: The interfaces related to the WebGLRenderingContext are referenced under WebGL.

+
+ +

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

+ +

Guides and tutorials

+ +
+
Canvas tutorial
+
A comprehensive tutorial covering both the basic usage of the Canvas API and its advanced features.
+
HTML5 Canvas Deep Dive
+
A hands-on, book-length introduction to the Canvas API and WebGL.
+
Canvas Handbook
+
A handy reference for the Canvas API.
+
Demo: A basic ray-caster
+
A demo of ray-tracing animation using canvas.
+
Manipulating video using canvas
+
Combining {{HTMLElement("video")}} and {{HTMLElement("canvas")}} to manipulate video data in real time.
+
+ +

Libraries

+ +

The Canvas API is extremely powerful, but not always simple to use. The libraries listed below can make the creation of canvas-based projects faster and easier.

+ + + +
+

Note: See the WebGL API for 2D and 3D libaries that use WebGL.

+
+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#2dcontext', 'the 2D rendering context')}}{{Spec2('HTML WHATWG')}}
+ +

Browser compatibility

+ +

Mozilla applications gained support for <canvas> starting with Gecko 1.8 (Firefox 1.5). The element was originally introduced by Apple for the OS X Dashboard and Safari. Internet Explorer supports <canvas> from version 9 onwards; for earlier versions of IE, a page can effectively add support for <canvas> by including a script from Google's Explorer Canvas project. Google Chrome and Opera 9 also support <canvas>.

+ +

See also

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

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

+ +

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

+ +

Properties

+ +

There are neither inherited, nor specific properties.

+ +

Methods

+ +

There are no inherited methods.

+ +
+
{{domxref("ChildNode.remove()")}} {{experimental_inline}}
+
Removes this ChildNode from the children list of its parent.
+
{{domxref("ChildNode.before()")}} {{experimental_inline}}
+
Inserts a set of {{domxref("Node")}} or {{domxref("DOMString")}} objects in the children list of this ChildNode's parent, just before this ChildNode. {{domxref("DOMString")}} objects are inserted as equivalent {{domxref("Text")}} nodes.
+
{{domxref("ChildNode.after()")}} {{experimental_inline}}
+
Inserts a set of {{domxref("Node")}} or {{domxref("DOMString")}} objects in the children list of this ChildNode's parent, just after this ChildNode. {{domxref("DOMString")}} objects are inserted as equivalent {{domxref("Text")}} nodes.
+
{{domxref("ChildNode.replaceWith()")}} {{experimental_inline}}
+
Replaces this ChildNode in the children list of its parent with a set of {{domxref("Node")}} or {{domxref("DOMString")}} objects. {{domxref("DOMString")}} objects are inserted as equivalent {{domxref("Text")}} nodes.
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG', '#interface-childnode', 'ChildNode')}}{{Spec2('DOM WHATWG')}}Split the ElementTraversal interface in {{domxref("ParentNode")}} and ChildNode. previousElementSibling and nextElementSibling are now defined on the latter. The {{domxref("CharacterData")}} and {{domxref("DocumentType")}} implemented the new interfaces. Added the remove(), before(), after() and replaceWith() methods.
{{SpecName('Element Traversal', '#interface-elementTraversal', 'ElementTraversal')}}{{Spec2('Element Traversal')}}Added the initial definition of its properties to the ElementTraversal pure interface and use it on {{domxref("Element")}}.
+ +

Polyfill

+ +

External on github: childNode.js

+ +

Browser compatibility

+ + + +

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

+ +

See also

+ + diff --git a/files/vi/web/api/childnode/remove/index.html b/files/vi/web/api/childnode/remove/index.html new file mode 100644 index 0000000000..3c0fde3e18 --- /dev/null +++ b/files/vi/web/api/childnode/remove/index.html @@ -0,0 +1,97 @@ +--- +title: ChildNode.remove() +slug: Web/API/ChildNode/remove +tags: + - API + - ChildNode + - DOM + - Phương Thức + - Đang thử nghiệm +translation_of: Web/API/ChildNode/remove +--- +
{{APIRef("DOM")}}
+ +

Phương thức ChildNode.remove() dùng để loại bỏ chính đối tượng gọi nó ra khỏi cây cấu trúc.

+ +

Cú pháp

+ +
node.remove();
+
+ +

Ví dụ

+ +

Cách dùng remove()

+ +
<div id="div-01">Đây là div-01</div>
+<div id="div-02">Đây là div-02</div>
+<div id="div-03">Đây là div-03</div>
+
+ +
var el = document.getElementById('div-02');
+el.remove(); // Gỡ bỏ div có id là 'div-02'
+
+ +

ChildNode.remove() is unscopable

+ +

The remove() method is not scoped into the with statement. See {{jsxref("Symbol.unscopables")}} for more information.

+ +
with(node) {
+  remove();
+}
+// ReferenceError: remove is not defined 
+ +

Giải pháp thay thế

+ +

Ta có thể thay thế phương thức remove() bằng đoạn mã sau để chạy trên Internet Explorer 9 và những đời sau này:

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

Thông số kỹ thuật

+ + + + + + + + + + + + + + +
Thông số kỹ thuậtTrạng tháiChú thích
{{SpecName('DOM WHATWG', '#dom-childnode-remove', 'ChildNode.remove')}}{{Spec2('DOM WHATWG')}}Lần đầu được định nghĩa.
+ +

Tính tương thích trên trình duyệt

+ +
+ + +

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

+
+ +

Xem thêm

+ + diff --git a/files/vi/web/api/document_object_model/index.html b/files/vi/web/api/document_object_model/index.html new file mode 100644 index 0000000000..d00ed4aeea --- /dev/null +++ b/files/vi/web/api/document_object_model/index.html @@ -0,0 +1,387 @@ +--- +title: Document Object Model (DOM) +slug: Web/API/Document_Object_Model +tags: + - API + - DOM + - DOM Reference + - Intermediate + - NeedsTranslation + - Reference + - TopicStub +translation_of: Web/API/Document_Object_Model +--- +

{{DefaultAPISidebar("DOM")}}

+ +

The Document Object Model (DOM) is a programming interface for HTML, XML and SVG documents. It provides a structured representation of the document as a tree. The DOM defines methods that allow access to the tree, so that they can change the document structure, style and content. The DOM provides a representation of the document as a structured group of nodes and objects, possessing various properties and methods. Nodes can also have event handlers attached to them, and once an event is triggered, the event handlers get executed. Essentially, it connects web pages to scripts or programming languages.

+ +

Although the DOM is often accessed using JavaScript, it is not a part of the JavaScript language. It can also be accessed by other languages.

+ +

An introduction to the DOM is available.

+ +

DOM interfaces

+ +
+ +
+ +

Obsolete DOM interfaces

+ +

The Document Object Model has been highly simplified. To achieve this, the following interfaces present in the different DOM level 3 or earlier specification have been removed. It is still not very clear whether some may be reintroduced or not, but for the time being they have to be considered as obsolete and should be avoided:

+ +
+ +
+ +

HTML interfaces

+ +

A document containing HTML is described using the {{domxref("HTMLDocument")}} interface. Note that the HTML specification also extends the {{domxref("Document")}} interface.

+ +

An HTMLDocument object also gives access to various features of browsers  like the tab or the window, in which a page is drawn using the {{domxref("Window")}} interface, the {{domxref("window.style", "Style")}} associated to it (usually CSS), the history of the browser relative to the context, {{domxref("window.history", "History")}}. Eventually, {{domxref("Selection")}} is done on the document.

+ +

HTML element interfaces

+ +
+ +
+ +

Other interfaces

+ +
+ +
+ +

Obsolete HTML interfaces

+ +
+ +
+ +

SVG interfaces

+ +

SVG element interfaces

+ +
+ +
+ +

SVG data type interfaces

+ +

Here are the DOM API for data types used in the definitions of SVG properties and attributes.

+ +
+

Note: Starting in {{Gecko("5.0")}}, the following SVG-related DOM interfaces representing lists of objects are now indexable and can be accessed ; in addition, they have a length property indicating the number of items in the lists: {{domxref("SVGLengthList")}}, {{domxref("SVGNumberList")}}, {{domxref("SVGPathSegList")}}, and {{domxref("SVGPointList")}}.

+
+ +

Static type

+ +
+ +
+ +

Animated type

+ +
+ +
+ + + +
+ +
+ +

Other SVG interfaces

+ +
+ +
+ +

See also

+ + diff --git a/files/vi/web/api/document_object_model/introduction/index.html b/files/vi/web/api/document_object_model/introduction/index.html new file mode 100644 index 0000000000..7a1ef163ee --- /dev/null +++ b/files/vi/web/api/document_object_model/introduction/index.html @@ -0,0 +1,223 @@ +--- +title: Introduction to the DOM +slug: Web/API/Document_Object_Model/Introduction +translation_of: Web/API/Document_Object_Model/Introduction +--- +

Phần này cung cấp một giới thiệu khái niệm ngắn gọn về DOM: nó là gì, nó cung cấp cấu trúc cho HTML và XML như thế nào, bạn có thể truy cập nó thế nào, và API này trình bày thông tin và các ví dụ tham khảo.

+ +

DOM là gì?

+ +

The Document Object Model (DOM) là một giao diện lập trình cho tài liệu HTML và XML. Nó cung cấp đại diện cấu trúc của tài liệu và nó xác định con đường mà cấu trúc có thể được truy cập từ các chương trình để chúng có thể thay đổi cấu trúc, phong cách và nội dung tài liệu. DOM cung cấp một sự trình bày của tài liệu như một nhóm cấu trúc của các nút và đối tượng mà có các thuộc tính và phương thức. Về cơ bản, nó kết nối các trang web tới các đoạn mã hay các ngôn ngữ lập trình.

+ +

Một trang Web là một tài liệu. Tài liệu này có thể hoặc là được hiển thị trong cửa sổ trình duyệt hoặc là như mã nguồn HTML. Nhưng nó cùng là tài liệu trong cả hai trường hợp. The Document Object Model (DOM) cung cấp cách khác để hiển thị, lưu trữ và thao tác cùng tài liệu. DOM là một đại diện hướng đối tượng hoàn toàn của trang web, và nó có thể được chỉnh sửa với một ngôn ngữ kịch bản như JavaScript.

+ +

Các tiêu chuẩn W3C DOM và WHATWG DOM tạo thành nền tảng của DOM được thực hiện trong hầu hết các trình duyệt hiện đại . Nhiều trình duyệt cung cấp các mở rộng bên ngoài chuẩn, nên phải cẩn thận khi sử dụng chúng trên web nơi các tài liệu có thể được truy cập bởi các trình duyệt khác nhau với các DOM khác nhau.

+ +

Ví dụ, DOM chuẩn quy định rằng phương thức getElementsByTagName trong code bên dưới phải trả về một danh sách của tất cả phần tử <p> trong tài liệu:

+ +
var paragraphs = document.getElementsByTagName("P");
+// paragraphs[0] is the first <p> element
+// paragraphs[1] is the second <p> element, etc.
+alert(paragraphs[0].nodeName);
+
+ +

Tất cả các thuộc tính, phương thức và sự kiện được sử dụng để thao tác và tạo ra các trang web được tổ chức dưới dạng các đối tượng (objects) (vd: đối tượng document đại diện cho trang tài liệu, đối tượng table kế thừa từ HTMLTableElement, một DOM interface đặc thù, cho phép truy cập HTML tables, v.v...). Phần này sẽ giới thiệu từng đối tượng DOM, được kế thừa trong các trình duyệt chạy trên nền Gecko.

+ +

DOM and JavaScript

+ +

The short example above, like nearly all of the examples in this reference, is JavaScript. That is to say, it's written in JavaScript, but it uses the DOM to access the document and its elements. The DOM is not a programming language, but without it, the JavaScript language wouldn't have any model or notion of web pages, HTML documents, XML documents, and their component parts (e.g. elements). Every element in a document—the document as a whole, the head, tables within the document, table headers, text within the table cells—is part of the document object model for that document, so they can all be accessed and manipulated using the DOM and a scripting language like JavaScript.

+ +

In the beginning, JavaScript and the DOM were tightly intertwined, but eventually they evolved into separate entities. The page content is stored in the DOM and may be accessed and manipulated via JavaScript, so that we may write this approximative equation:

+ +

API (HTML or XML page) = DOM + JS (scripting language)

+ +

The DOM was designed to be independent of any particular programming language, making the structural representation of the document available from a single, consistent API. Though we focus exclusively on JavaScript in this reference documentation, implementations of the DOM can be built for any language, as this Python example demonstrates:

+ +
# Python DOM example
+import xml.dom.minidom as m
+doc = m.parse("C:\\Projects\\Py\\chap1.xml");
+doc.nodeName # DOM property of document object;
+p_list = doc.getElementsByTagName("para");
+
+ +

For more information on what technologies are involved in writing JavaScript on the web, see JavaScript technologies overview.

+ +

How Do I Access the DOM?

+ +

You don't have to do anything special to begin using the DOM. Different browsers have different implementations of the DOM, and these implementations exhibit varying degrees of conformance to the actual DOM standard (a subject we try to avoid in this documentation), but every web browser uses some document object model to make web pages accessible to script.

+ +

When you create a script–whether it's inline in a <script> element or included in the web page by means of a script loading instruction–you can immediately begin using the API for the document or window elements to manipulate the document itself or to get at the children of that document, which are the various elements in the web page. Your DOM programming may be something as simple as the following, which displays an alert message by using the alert() function from the window object, or it may use more sophisticated DOM methods to actually create new content, as in the longer example below.

+ +
<body onload="window.alert('Welcome to my home page!');">
+
+ +

Aside from the <script> element in which the JavaScript is defined, this JavaScript sets a function to run when the document is loaded (and when the whole DOM is available for use). This function creates a new H1 element, adds text to that element, and then adds the H1 to the tree for this document:

+ +
<html>
+  <head>
+    <script>
+       // run this function when the document is loaded
+       window.onload = function() {
+
+         // create a couple of elements in an otherwise empty HTML page
+         var heading = document.createElement("h1");
+         var heading_text = document.createTextNode("Big Head!");
+         heading.appendChild(heading_text);
+         document.body.appendChild(heading);
+      }
+    </script>
+  </head>
+  <body>
+  </body>
+</html>
+
+ +

Important Data Types

+ +

This reference tries to describe the various objects and types in as simple a way as possible. But there are a number of different data types being passed around the API that you should be aware of. For the sake of simplicity, syntax examples in this API reference typically refer to nodes as elements, to arrays of nodes as nodeLists (or simply elements), and to attribute nodes simply as attributes.

+ +

The following table briefly describes these data types.

+ + + + + + + + + + + + + + + + + + + + + + + + +
documentWhen a member returns an object of type document (e.g., the ownerDocument property of an element returns the document to which it belongs), this object is the root document object itself. The DOM document Reference chapter describes the document object.
elementelement refers to an element or a node of type element returned by a member of the DOM API. Rather than saying, for example, that the document.createElement() method returns an object reference to a node, we just say that this method returns the element that has just been created in the DOM. element objects implement the DOM Element interface and also the more basic Node interface, both of which are included together in this reference.
nodeListA nodeList is an array of elements, like the kind that is returned by the method document.getElementsByTagName(). Items in a nodeList are accessed by index in either of two ways: +
    +
  • list.item(1)
  • +
  • list[1]
  • +
+ These two are equivalent. In the first, item() is the single method on the nodeList object. The latter uses the typical array syntax to fetch the second item in the list.
attributeWhen an attribute is returned by a member (e.g., by the createAttribute() method), it is an object reference that exposes a special (albeit small) interface for attributes. Attributes are nodes in the DOM just like elements are, though you may rarely use them as such.
namedNodeMapA namedNodeMap is like an array, but the items are accessed by name or index, though this latter case is merely a convenience for enumeration, as they are in no particular order in the list. A namedNodeMap has an item() method for this purpose, and you can also add and remove items from a namedNodeMap.
+ +

DOM interfaces

+ +

This guide is about the objects and the actual things you can use to manipulate the DOM hierarchy. There are many points where understanding how these work can be confusing. For example, the object representing the HTML form element gets its name property from the HTMLFormElement interface but its className property from the HTMLElement interface proper. In both cases, the property you want is simply in that form object.

+ +

But the relationship between objects and the interfaces that they implement in the DOM can be confusing, and so this section attempts to say a little something about the actual interfaces in the DOM specification and how they are made available.

+ +

Interfaces and Objects

+ +

Many objects borrow from several different interfaces. The table object, for example, implements a specialized HTML Table Element Interface, which includes such methods as createCaption and insertRow. But since it's also an HTML element, table implements the Element interface described in the DOM element Reference chapter. And finally, since an HTML element is also, as far as the DOM is concerned, a node in the tree of nodes that make up the object model for an HTML or XML page, the table element also implements the more basic Node interface, from which Element derives.

+ +

When you get a reference to a table object, as in the following example, you routinely use all three of these interfaces interchangeably on the object, perhaps without knowing it.

+ +
var table = document.getElementById("table");
+var tableAttrs = table.attributes; // Node/Element interface
+for (var i = 0; i < tableAttrs.length; i++) {
+  // HTMLTableElement interface: border attribute
+  if(tableAttrs[i].nodeName.toLowerCase() == "border")
+    table.border = "1";
+}
+// HTMLTableElement interface: summary attribute
+table.summary = "note: increased border";
+
+ +

Core Interfaces in the DOM

+ +

This section lists some of the most commonly-used interfaces in the DOM. The idea is not to describe what these APIs do here but to give you an idea of the sorts of methods and properties you will see very often as you use the DOM. These common APIs are used in the longer examples in the DOM Examples chapter at the end of this book.

+ +

Document and window objects are the objects whose interfaces you generally use most often in DOM programming. In simple terms, the window object represents something like the browser, and the document object is the root of the document itself. Element inherits from the generic Node interface, and together these two interfaces provide many of the methods and properties you use on individual elements. These elements may also have specific interfaces for dealing with the kind of data those elements hold, as in the table object example in the previous section.

+ +

The following is a brief list of common APIs in web and XML page scripting using the DOM.

+ + + +

Testing the DOM API

+ +

This document provides samples for every interface that you can use in your own web development. In some cases, the samples are complete HTML pages, with the DOM access in a <script> element, the interface (e.g, buttons) necessary to fire up the script in a form, and the HTML elements upon which the DOM operates listed as well. When this is the case, you can cut and paste the example into a new HTML document, save it, and run the example from the browser.

+ +

There are some cases, however, when the examples are more concise. To run examples that only demonstrate the basic relationship of the interface to the HTML elements, you may want to set up a test page in which interfaces can be easily accessed from scripts. The following very simple web page provides a <script> element in the header in which you can place functions that test the interface, a few HTML elements with attributes that you can retrieve, set, or otherwise manipulate, and the web user interface necessary to call those functions from the browser.

+ +

You can use this test page or create a similar one to test the DOM interfaces you are interested in and see how they work on the browser platform. You can update the contents of the test() function as needed, create more buttons, or add elements as necessary.

+ +
<html>
+  <head>
+    <title>DOM Tests</title>
+    <script type="application/javascript">
+    function setBodyAttr(attr, value){
+      if (document.body) eval('document.body.'+attr+'="'+value+'"');
+      else notSupported();
+    }
+    </script>
+  </head>
+  <body>
+    <div style="margin: .5in; height: 400;">
+      <p><b><tt>text</tt></b></p>
+      <form>
+        <select onChange="setBodyAttr('text',
+        this.options[this.selectedIndex].value);">
+          <option value="black">black
+          <option value="darkblue">darkblue
+        </select>
+        <p><b><tt>bgColor</tt></b></p>
+        <select onChange="setBodyAttr('bgColor',
+        this.options[this.selectedIndex].value);">
+          <option value="white">white
+          <option value="lightgrey">gray
+        </select>
+        <p><b><tt>link</tt></b></p>
+        <select onChange="setBodyAttr('link',
+        this.options[this.selectedIndex].value);">
+          <option value="blue">blue
+          <option value="green">green
+        </select>  <small>
+        <a href="http://www.brownhen.com/dom_api_top.html" id="sample">
+        (sample link)</a></small><br>
+      </form>
+      <form>
+        <input type="button" value="version" onclick="ver()" />
+      </form>
+    </div>
+  </body>
+</html>
+
+ +

To test a lot of interfaces in a single page-for example, a "suite" of properties that affect the colors of a web page-you can create a similar test page with a whole console of buttons, textfields, and other HTML elements. The following screenshot gives you some idea of how interfaces can be grouped together for testing.

+ +
+
Figure 0.1 Sample DOM Test Page
+Image:DOM_Ref_Introduction_to_the_DOM.gif
+ +

In this example, the dropdown menus dynamically update such DOM-accessible aspects of the web page as its background color (bgColor), the color of the hyperlinks (aLink), and color of the text (text). However you design your test pages, testing the interfaces as you read about them is an important part of learning how to use the DOM effectively.

+ + + + diff --git a/files/vi/web/api/eventsource/index.html b/files/vi/web/api/eventsource/index.html new file mode 100644 index 0000000000..36a35382dd --- /dev/null +++ b/files/vi/web/api/eventsource/index.html @@ -0,0 +1,127 @@ +--- +title: EventSource +slug: Web/API/EventSource +tags: + - API + - Communications + - EventSource + - Interface + - NeedsTranslation + - Reference + - Server Sent Events + - Server-sent events + - TopicStub + - messaging +translation_of: Web/API/EventSource +--- +
{{APIRef("Server Sent Events")}}
+ +

The EventSource interface is web content's interface to server-sent events. An EventSource instance opens a persistent connection to an HTTP server, which sends events in text/event-stream format. The connection remains open until closed by calling {{domxref("EventSource.close()")}}.

+ +

Once the connection is opened, incoming messages from the server are delivered to your code in the form of {{event("message")}} events.

+ +

Unlike WebSockets, server-sent events are unidirectional; that is, data messages are delivered in one direction, from the server to the client (such as a user's web browser). That makes them an excellent choice when there's no need to send data from the client to the server in message form. For example, EventSource is a useful approach for handling things like social media status updates, news feeds, or delivering data into a client-side storage mechanism like IndexedDB or web storage.

+ +

Constructor

+ +
+
{{domxref("EventSource.EventSource", "EventSource()")}}
+
Creates a new EventSource to handle receiving server-sent events from a specified URL, optionally in credentials mode.
+
+ +

Properties

+ +

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

+ +
+
{{domxref("EventSource.readyState")}} {{readonlyinline}}
+
A number representing the state of the connection. Possible values are CONNECTING (0), OPEN (1), or CLOSED (2).
+
{{domxref("EventSource.url")}} {{readonlyinline}}
+
A {{domxref("DOMString")}} representing the URL of the source.
+
{{domxref("EventSource.withCredentials")}} {{readonlyinline}}
+
A {{domxref("Boolean")}} indicating whether the EventSource object was instantiated with cross-origin (CORS) credentials set (true), or not (false, the default).
+
+ +

Event handlers

+ +
+
{{domxref("EventSource.onerror")}}
+
Is an {{domxref("EventHandler")}} called when an error occurs and the {{domxref("EventSource/error_event", "error")}} event is dispatched on an EventSource object.
+
{{domxref("EventSource.onmessage")}}
+
Is an {{domxref("EventHandler")}} called when a {{domxref("EventSource/message_event", "message")}} event is received, that is when a message is coming from the source.
+
{{domxref("EventSource.onopen")}}
+
Is an {{domxref("EventHandler")}} called when an {{domxref("EventSource/open_event", "open")}} event is received, that is when the connection was just opened.
+
+ +

Methods

+ +

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

+ +
+
{{domxref("EventSource.close()")}}
+
Closes the connection, if any, and sets the readyState attribute to CLOSED. If the connection is already closed, the method does nothing.
+
+ +

Events

+ +
+
{{domxref("EventSource/error_event", "error")}}
+
Fired when a connection to an event source failed to open.
+
{{domxref("EventSource/message_event", "message")}}
+
Fired when data is received from an event source.
+
{{domxref("EventSource/open_event", "open")}}
+
Fired when a connection to an event source has opened.
+
+ +

Examples

+ +

In this basic example, an EventSource is created to receive events from the server; a page with the name sse.php is responsible for generating the events.

+ +
var evtSource = new EventSource('sse.php');
+var eventList = document.querySelector('ul');
+
+evtSource.onmessage = function(e) {
+  var newElement = document.createElement("li");
+
+  newElement.textContent = "message: " + e.data;
+  eventList.appendChild(newElement);
+}
+ +

Each received event causes our EventSource object's onmessage event handler to be run. It, in turn, creates a new {{HTMLElement("li")}} element and writes the message's data into it, then appends the new element to the list element already in the document.

+ +
+

Note: You can find a full example on GitHub — see Simple SSE demo using PHP.

+
+ +

Specifications

+ + + + + + + + + + + + +
SpecificationStatus
{{SpecName('HTML WHATWG', "comms.html#the-eventsource-interface", "EventSource")}}{{Spec2('HTML WHATWG')}}
+ + + +

Browser compatibility

+ +
+ + +

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

+
+ +

See also

+ + diff --git a/files/vi/web/api/eventsource/url/index.html b/files/vi/web/api/eventsource/url/index.html new file mode 100644 index 0000000000..2af6554db0 --- /dev/null +++ b/files/vi/web/api/eventsource/url/index.html @@ -0,0 +1,59 @@ +--- +title: EventSource.url +slug: Web/API/EventSource/url +translation_of: Web/API/EventSource/url +--- +
{{APIRef('WebSockets API')}}
+ +

url là thuộc tính chỉ đọc của giao diện {{domxref("EventSource")}} trả về {{domxref("DOMString")}} đại diện cho URL của nguồn.

+ +

Cú pháp

+ +
var myUrl = eventSource.url;
+ +

Giá trị

+ +

{{domxref("DOMString")}} đại diện cho URL của nguồn.

+ +

Ví dụ

+ +
var evtSource = new EventSource('sse.php');
+console.log(evtSource.url);
+ +
+

Ghi chú: bạn có thể xem ví dụ đầy đủ trên GitHub — xem Simple SSE demo using PHP.

+
+ +

Thông số kĩ thuật

+ + + + + + + + + + + + + + +
Thông số kĩ thuậtTrạng tháiChú thích
{{SpecName('HTML WHATWG', "comms.html#dom-eventsource-url", "url")}}{{Spec2('HTML WHATWG')}}Định nghĩa ban đầu
+ + + +

Trình duyệt tương thích

+ +
+ + +

{{Compat("api.EventSource.url")}}

+
+ +

Liên quan

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

The Fetch API cung cấp giao diện để tìm nạp tài nguyên (bao gồm thông qua mạng). It will seem familiar to anyone who has used {{DOMxRef("XMLHttpRequest")}}, but the new API provides a more powerful and flexible feature set.

+ +

Concepts and usage

+ +

Fetch cung cấp một định nghĩa chung về các đối tượng {{DOMxRef("Request")}} and {{DOMxRef("Response")}} (và mọi thứ khác liên quan đến các request network). Điều này cho phép chúng được sử dụng ở bất cứ nơi nào cần chúng trong tương lai, cho dù đó là service workers, Cache API, và những thứ tương tự khác mà có khả năng xử lý hoặc sửa đổi các request và responses, hoặc bất kỳ trường hợp nào mà yêu cầu bạn tự tạo ra responses trong chương trình của chính mình.

+ +

Nó cũng cung cấp một định nghĩa cho các khái niệm liên quan như CORS and the HTTP Header, thay thế các định nghĩa riêng biệt của chúng ở nơi khác.

+ +

Để thực hiện một request và tìm nạp tài nguyên, use the {{DOMxRef("WindowOrWorkerGlobalScope.fetch()")}} method. Nó được triển khai trong nhiều interfaces, đặc biệt là {{DOMxRef("Window")}} và {{DOMxRef("WorkerGlobalScope")}}. Điều này làm cho nó có sẵn trong hầu hết mọi ngữ cảnh mà bạn có thể muốn tìm nạp tài nguyên.

+ +

The fetch() method có một đối số bắt buộc, đó chính là đường dẫn đến tài nguyên bạn tìm nạp. Nó returns a {{DOMxRef("Promise")}} thứ mà sẽ giải quyết và đưa ra một {{DOMxRef("Response")}} cho request đó, bất kể là thành công hay thất bại. Bạn có thể tùy chỉnh việc truyền một đối tượng tùy chỉnh init như là một đối số thữ hai (see {{DOMxRef("Request")}}).

+ +

Cho đến khi một {{DOMxRef("Response")}} được truy xuất, có một số methods có sẵn để xác định nội dung body là gì và cách nó được xử lý như thế nào. (see {{DOMxRef("Body")}}).

+ +

Bạn có thể tạo ra một request và response trực tiếp bằng cách sử dụng {{DOMxRef("Request.Request", "Request()")}} và {{DOMxRef("Response.Response", "Response()")}} constructors, nhưng cách làm này là không phổ biến. Thay vào đó, những thứ này có thể được tạo ra bằng cách là kết quả trả về của các hành động API khác (ví dụ, {{DOMxRef("FetchEvent.respondWith()")}} from service workers).

+ +

Differences from jQuery

+ +

The fetch khác với jQuery.ajax() in ba điểm chính sau:

+ + + +
+

Note: Tìm hiểu thêm về cách sử dụng Fetch API tại Using Fetch, và học các khái niệm tại  Fetch basic concepts.

+
+ +

Huỷ bỏ fetch

+ +

Browsers have started to add experimental support for the {{DOMxRef("AbortController")}} and {{DOMxRef("AbortSignal")}} interfaces (aka The Abort API), which allow operations like Fetch and XHR to be aborted if they have not already completed. See the interface pages for more details.

+ +

Fetch Interfaces

+ +
+
{{DOMxRef("WindowOrWorkerGlobalScope.fetch()")}}
+
The fetch() method được sử dụng để tìm nạp tài nguyên.
+
{{DOMxRef("Headers")}}
+
Đại diện cho các response/request headers, cho phép bạn truy vấn chúng and thực hiện các hành động khác nhau phụ thuộc vào các kết quả..
+
{{DOMxRef("Request")}}
+
Đại điện cho một request tài nguyên.
+
{{DOMxRef("Response")}}
+
Đại điện cho một Response của một Request.
+
+ +

Fetch mixin

+ +
+
{{DOMxRef("Body")}}
+
Cung cấp các methods liên quan đến body của response/request, cho phép bạn khai báo kiểu nội dung của chúng và cách chúng được xử lý.
+
+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("Fetch")}}{{Spec2("Fetch")}}Initial definition
+ +

Browser compatibility

+ + + +

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

+ +

See also

+ + diff --git a/files/vi/web/api/file/index.html b/files/vi/web/api/file/index.html new file mode 100644 index 0000000000..3722df4e46 --- /dev/null +++ b/files/vi/web/api/file/index.html @@ -0,0 +1,99 @@ +--- +title: File +slug: Web/API/File +tags: + - API + - File API + - Interface + - Reference + - Web +translation_of: Web/API/File +--- +
{{APIRef}}
+ +

File cung cấp thông tin về các tệp và cho phép Javascript truy cập nội dung của chúng.

+ +

File thường được lấy từ một {{DOMxRef("FileList")}} đối tượng trả về như là kết quả của người dùng chọn files sử dụng phần tử {{HTMLElement("input")}}, từ thao tác kéo và thả đối tượng {{DOMxRef("DataTransfer")}}, hoặc là từ mozGetAsFile() API trên một {{DOMxRef("HTMLCanvasElement")}}.

+ +

Đối tượng file là một loại {{DOMxRef("Blob")}}, và có thể sử dụng trong mọi hoàn cảnh mà Blob có thể sử dụng. Cụ thể, {{DOMxRef("FileReader")}}, {{DOMxRef("URL.createObjectURL()")}}, {{DOMxRef("ImageBitmapFactories.createImageBitmap()", "createImageBitmap()")}}, và {{DOMxRef("XMLHttpRequest", "", "send()")}} chấp nhận cả Blobs và Files.

+ +

Đọc Using files from web applications để biết thêm thông tin và ví dụ.

+ +

{{InheritanceDiagram}}

+ +

Constructor

+ +
+
{{DOMxRef("File.File", "File()")}}
+
Trả về một constructed File mới.
+
+ +

Thuộc tính

+ +
+
{{DOMxRef("File.lastModified")}} {{ReadOnlyInline}}
+
Trả về thời gian sửa đổi cuối cùng của file, tính bằng mili giây kể từ kỉ nguyên UNIX (January 1st, 1970 at Midnight).
+
{{DOMxRef("File.lastModifiedDate")}} {{Deprecated_Inline}} {{ReadOnlyInline}}
+
Returns the last modified {{JSxRef("Date")}} of the file referenced by the File object.
+
{{DOMxRef("File.name")}}{{ReadOnlyInline}}
+
Trả về tên của tệp referenced by the File object.
+
{{DOMxRef("File.webkitRelativePath")}} {{Non-standard_Inline}} {{ReadOnlyInline}}
+
Trả về đường dẫn (URL) của {{DOMxRef("File")}} có liên quan.
+
+ +

File bổ sung {{DOMxRef("Blob")}}, Vì vậy, nó cũng có các thuộc tính có sẵn:

+ +
+
{{DOMxRef("File.size")}} {{ReadOnlyInline}}
+
Trả về kích thước của file (tính bằng bytes)
+
{{DOMxRef("File.type")}} {{ReadOnlyInline}}
+
Trả về thể loại MIME của file file.
+
+ +

Phương thức

+ +

File không có phương thức nào, nhưng nó thừa kế từ {{DOMxRef("Blob")}}:

+ +
+
{{DOMxRef("Blob.slice()", "Blob.slice([start[, end[, contentType]]])")}}
+
Trả về một đối tượng Blob mới có nội dung trong phạm vi bytes chỉ định của Blob
+
{{DOMxRef("Blob.stream()")}}
+
Chuyển đổi file thành {{DOMxRef("ReadableStream")}} vì vậy có thể sử dụng để đọc nội dung file.
+
{{DOMxRef("Blob.text()")}}
+
Chuyển đổi file thành stream và đọc nó để hoàn thành. Nó trả về một promise có thể giải quyết với {{DOMxRef("USVString")}} (text).
+
{{DOMxRef("Blob.arrayBuffer()")}}
+
Chuyển đổi file thành stream và đọc nó để hoàn thành. Nó trả về một promise có thể giải quyết với {{DOMxRef("ArrayBuffer")}}.
+
+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('File API', "#file-section", "The File interface")}}{{Spec2('File API')}}Initial definition.
+ +

Browser compatibility

+ + + +

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

+ +

Xem thêm

+ + diff --git a/files/vi/web/api/geolocation_api/index.html b/files/vi/web/api/geolocation_api/index.html new file mode 100644 index 0000000000..0286a06249 --- /dev/null +++ b/files/vi/web/api/geolocation_api/index.html @@ -0,0 +1,244 @@ +--- +title: Geolocation API +slug: Web/API/Geolocation_API +translation_of: Web/API/Geolocation_API +--- +

{{securecontext_header}} {{APIRef("API định vị địa lý")}}

+ +

Các API Định vị cho phép người dùng để cung cấp vị trí của họ vào các ứng dụng web nếu họ mong muốn. Vì lý do riêng tư, người dùng được yêu cầu cho phép báo cáo thông tin vị trí.

+ +

Đối tượng định vị địa lý

+ +

Các Định vị API được công bố thông qua {{domxref( "navigator.geolocation")}} đối tượng.

+ +

Nếu đối tượng tồn tại, dịch vụ định vị địa lý có sẵn. Do đó, bạn có thể kiểm tra sự hiện diện của vị trí địa lý:

+ +
if ("geolocation" in navigator) {
+  / * định vị địa lý có sẵn * /
+} else {
+  / * định vị địa lý KHÔNG có sẵn * /
+}
+
+ +
+

Lưu ý: Trên Firefox 24 và các phiên bản cũ hơn, "geolocation" in navigatorluôn được trả về truengay cả khi API bị tắt. Điều này đã được sửa với Firefox 25 để tuân thủ thông số kỹ thuật. ({{bug(884921)}}).

+
+ +

Lấy vị trí hiện tại

+ +

Để có được vị trí hiện tại của người dùng, bạn có thể gọi phương thức {{domxref("geolocation.getCurrentPosition()", "getCurrentPosition()")}}. Điều này bắt đầu một yêu cầu không đồng bộ để phát hiện vị trí của người dùng và truy vấn phần cứng định vị để có được thông tin cập nhật. Khi vị trí được xác định, chức năng gọi lại được xác định sẽ được thực thi. Bạn có thể tùy chọn cung cấp chức năng gọi lại thứ hai để được thực thi nếu xảy ra lỗi. Tham số thứ ba, tùy chọn, là một đối tượng tùy chọn trong đó bạn có thể đặt tuổi tối đa của vị trí được trả về, thời gian chờ yêu cầu và nếu bạn muốn độ chính xác cao cho vị trí.

+ +
+

Lưu ý: Theo mặc định, {{domxref("Geolocation.getCurrentPosition ()", "getCurrentPosition()")}} cố gắng trả lời nhanh nhất có thể với kết quả chính xác thấp. Nó rất hữu ích nếu bạn cần một câu trả lời nhanh bất kể độ chính xác. Chẳng hạn, các thiết bị có GPS có thể mất một phút hoặc hơn để sửa lỗi GPS, do đó, dữ liệu kém chính xác hơn(vị trí IP hoặc wifi) có thể được trả về {{domxref("Geolocation.getCurrentPosition()", "getCurrentPosition() ")}}.

+
+ +
navigator.geolocation.getCurrentPosition(function(position) {
+  do_something(location.coords.latitude, location.coords.longitude);
+});
+ +

Ví dụ trên sẽ khiến do_something()hàm thực thi khi lấy được vị trí.

+ +

Xem vị trí hiện tại

+ +

Nếu dữ liệu vị trí thay đổi (theo chuyển động của thiết bị hoặc nếu có thông tin địa lý chính xác hơn), bạn có thể thiết lập chức năng gọi lại được gọi với thông tin vị trí được cập nhật đó. Điều này được thực hiện bằng cách sử dụng hàm {{domxref("Geolocation.watchPocation ()", "watchPosition()")}}, có cùng tham số đầu vào như {{domxref("Geolocation.getCurrentPosition()", "getCurrentPosition() ")}}. Chức năng gọi lại được gọi nhiều lần, cho phép trình duyệt cập nhật vị trí của bạn khi bạn di chuyển hoặc cung cấp vị trí chính xác hơn vì các kỹ thuật khác nhau được sử dụng để định vị địa lý cho bạn. Hàm gọi lại lỗi, là tùy chọn giống như đối với {{domxref("Geolocation.getCurrentPosition()", "getCurrentPosition()")}}, có thể được gọi lặp lại.

+ +
+

Lưu ý: Bạn có thể sử dụng {{domxref("Geolocation.watchPosition()", "watchPosition()")}} mà không cần một cuộc gọi {{domxref("Geolocation.getCienPocation ()", "getCienPocation ()")}}.

+
+ +
var watchID = navigator.geolocation.watchPosition(function(location) {
+  do_something(location.coords.latitude, location.coords.longitude);
+});
+ +

Phương thức {{domxref("Geolocation.watchPosition()", "watchPosition()")}} trả về số ID có thể được sử dụng để xác định duy nhất trình theo dõi vị trí được yêu cầu; bạn sử dụng giá trị này song song với phương thức {{domxref("Geolocation.clearWatch()", "clearWatch()")}} để dừng xem vị trí của người dùng.

+ +
navigator.geolocation.clearWatch(watchID);
+
+ +

Phản ứng tinh chỉnh

+ +

Both {{domxref("Geolocation.getCurrentPosition()","getCurrentPosition()")}} and {{domxref("Geolocation.watchPosition()","watchPosition()")}} accept a success callback, an optional error callback, and an optional PositionOptions object.

+ +

{{page("/en-US/docs/DOM/navigator.geolocation.getCurrentPosition","PositionOptions")}}

+ +

A call to {{domxref("Geolocation.watchPosition()","watchPosition")}} could look like:

+ +
function geo_success(position) {
+  do_something(position.coords.latitude, position.coords.longitude);
+}
+
+function geo_error() {
+  alert("Sorry, no position available.");
+}
+
+var geo_options = {
+  enableHighAccuracy: true,
+  maximumAge        : 30000,
+  timeout           : 27000
+};
+
+var wpid = navigator.geolocation.watchPosition(geo_success, geo_error, geo_options);
+ +

Describing a position

+ +

The user's location is described using a {{domxref("Position")}} object referencing a {{domxref("Coordinates")}} object.

+ +

{{page("/en-US/docs/DOM/navigator/geolocation/getCurrentPosition","Position")}}

+ +

{{page("/en-US/docs/DOM/navigator/geolocation/getCurrentPosition","Coordinates")}}

+ +

Handling errors

+ +

The error callback function, if provided when calling getCurrentPosition() or watchPosition(), expects a PositionError object as its first parameter.

+ +
function errorCallback(error) {
+  alert('ERROR(' + error.code + '): ' + error.message);
+};
+
+ +

{{page("/en-US/docs/DOM/navigator/geolocation/getCurrentPosition","PositionError")}}

+ +

Geolocation Live Example

+ + + +

HTML Content

+ +
<button id = "find-me">Show my location</button><br/>
+<p id = "status"></p>
+<a id = "map-link" target="_blank"></a>
+
+ +

JavaScript Content

+ +
function geoFindMe() {
+
+  const status = document.querySelector('#status');
+  const mapLink = document.querySelector('#map-link');
+
+  mapLink.href = '';
+  mapLink.textContent = '';
+
+  function success(position) {
+    const latitude  = position.coords.latitude;
+    const longitude = position.coords.longitude;
+
+    status.textContent = '';
+    mapLink.href = `https://www.openstreetmap.org/#map=18/${latitude}/${longitude}`;
+    mapLink.textContent = `Latitude: ${latitude} °, Longitude: ${longitude} °`;
+  }
+
+  function error() {
+    status.textContent = 'Unable to retrieve your location';
+  }
+
+  if (!navigator.geolocation) {
+    status.textContent = 'Geolocation is not supported by your browser';
+  } else {
+    status.textContent = 'Locating…';
+    navigator.geolocation.getCurrentPosition(success, error);
+  }
+
+}
+
+document.querySelector('#find-me').addEventListener('click', geoFindMe);
+
+ +

Live Result

+ +

{{EmbedLiveSample('Geolocation_Live_Example', 350, 150, "", "", "", "geolocation")}}

+ +

Prompting for permission

+ +

Any add-on hosted on addons.mozilla.org which makes use of geolocation data must explicitly request permission before doing so. The following function will request permission in a manner similar to the automatic prompt displayed for web pages. The user's response will be saved in the preference specified by the pref parameter, if applicable. The function provided in the callback parameter will be called with a boolean value indicating the user's response. If true, the add-on may access geolocation data.

+ +
function prompt(window, pref, message, callback) {
+    let branch = Components.classes["@mozilla.org/preferences-service;1"]
+                           .getService(Components.interfaces.nsIPrefBranch);
+
+    if (branch.getPrefType(pref) === branch.PREF_STRING) {
+        switch (branch.getCharPref(pref)) {
+        case "always":
+            return callback(true);
+        case "never":
+            return callback(false);
+        }
+    }
+
+    let done = false;
+
+    function remember(value, result) {
+        return function() {
+            done = true;
+            branch.setCharPref(pref, value);
+            callback(result);
+        }
+    }
+
+    let self = window.PopupNotifications.show(
+        window.gBrowser.selectedBrowser,
+        "geolocation",
+        message,
+        "geo-notification-icon",
+        {
+            label: "Share Location",
+            accessKey: "S",
+            callback: function(notification) {
+                done = true;
+                callback(true);
+            }
+        }, [
+            {
+                label: "Always Share",
+                accessKey: "A",
+                callback: remember("always", true)
+            },
+            {
+                label: "Never Share",
+                accessKey: "N",
+                callback: remember("never", false)
+            }
+        ], {
+            eventCallback: function(event) {
+                if (event === "dismissed") {
+                    if (!done) callback(false);
+                    done = true;
+                    window.PopupNotifications.remove(self);
+                }
+            },
+            persistWhileVisible: true
+        });
+}
+
+prompt(window,
+       "extensions.foo-addon.allowGeolocation",
+       "Foo Add-on wants to know your location.",
+       function callback(allowed) { alert(allowed); });
+
+ +

Browser compatibility

+ +

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

+ +

khả dụng

+ +

Vì định vị dựa trên WiFi thường được cung cấp bởi Google, API định vị vanilla có thể không khả dụng ở Trung Quốc. Bạn có thể sử dụng các nhà cung cấp bên thứ ba địa phương như Baidu , Autonavi hoặc Tencent . Các dịch vụ này sử dụng địa chỉ IP của người dùng và / hoặc ứng dụng cục bộ để cung cấp định vị nâng cao.

+ +

Xem thêm

+ + diff --git a/files/vi/web/api/htmlcanvaselement/getcontext/index.html b/files/vi/web/api/htmlcanvaselement/getcontext/index.html new file mode 100644 index 0000000000..b2478fba5d --- /dev/null +++ b/files/vi/web/api/htmlcanvaselement/getcontext/index.html @@ -0,0 +1,140 @@ +--- +title: HTMLCanvasElement.getContext() +slug: Web/API/HTMLCanvasElement/getContext +tags: + - TV +translation_of: Web/API/HTMLCanvasElement/getContext +--- +
{{APIRef("Canvas API")}}
+ +

The HTMLCanvasElement.getContext() method returns a drawing context on the canvas, or {{jsxref("null")}} if the context identifier is not supported.

+ +

Later calls to this method on the same canvas element return the same drawing context instance as was returned the last time the method was invoked with the same contextType argument. To get a different drawing context object you need to pass a different contextType or call the method on a different canvas element. 

+ +

Syntax

+ +
var ctx = canvas.getContext(contextType);
+var ctx = canvas.getContext(contextType, contextAttributes);
+
+ +

Parameters

+ +
+
contextType
+
Is a {{domxref("DOMString")}} containing the context identifier defining the drawing context associated to the canvas. Possible values are: +
    +
  • "2d", leading to the creation of a {{domxref("CanvasRenderingContext2D")}} object representing a two-dimensional rendering context.
  • +
  • "webgl" (or "experimental-webgl") which will create a {{domxref("WebGLRenderingContext")}} object representing a three-dimensional rendering context. This context is only available on browsers that implement WebGL version 1 (OpenGL ES 2.0).
  • +
  • "webgl2" which will create a {{domxref("WebGL2RenderingContext")}} object representing a three-dimensional rendering context. This context is only available on browsers that implement WebGL version 2 (OpenGL ES 3.0). {{experimental_inline}}
  • +
  • "bitmaprenderer" which will create an {{domxref("ImageBitmapRenderingContext")}} which only provides functionality to replace the content of the canvas with a given {{domxref("ImageBitmap")}}.
  • +
+ +
+

Note: The identifier "experimental-webgl" is used in new implementations of WebGL. These implementations have either not reached test suite conformance, or the graphics drivers on the platform are not yet stable. The Khronos Group certifies WebGL implementations under certain conformance rules.

+
+
+
contextAttributes
+
+

You can use several context attributes when creating your rendering context, for example:

+ +
const gl = canvas.getContext('webgl', {
+  antialias: false,
+  depth: false
+});
+ 2d context attributes: + +
    +
  • alpha: Boolean that indicates if the canvas contains an alpha channel. If set to false, the browser now knows that the backdrop is always opaque, which can speed up drawing of transparent content and images.
  • +
  • {{non-standard_inline}} (Gecko only) willReadFrequently: Boolean that indicates whether or not a lot of read-back operations are planned. This will force the use of a software (instead of hardware accelerated) 2D canvas and can save memory when calling {{domxref("CanvasRenderingContext2D.getImageData", "getImageData()")}} frequently. This option is only available, if the flag gfx.canvas.willReadFrequently.enable is set to true (which, by default, is only the case for B2G/Firefox OS).
  • +
  • {{non-standard_inline}} (Blink only) storage: String that indicates which storage is used ("persistent" by default).
  • +
+ WebGL context attributes: + +
    +
  • alpha: Boolean that indicates if the canvas contains an alpha buffer.
  • +
  • antialias: Boolean that indicates whether or not to perform anti-aliasing.
  • +
  • depth: Boolean that indicates that the drawing buffer has a depth buffer of at least 16 bits.
  • +
  • failIfMajorPerformanceCaveat: Boolean that indicates if a context will be created if the system performance is low.
  • +
  • powerPreference: A hint to the user agent indicating what configuration of GPU is suitable for the WebGL context. Possible values are: +
      +
    • "default": Let the user agent decide which GPU configuration is most suitable. This is the default value.
    • +
    • "high-performance": Prioritizes rendering performance over power consumption.
    • +
    • "low-power": Prioritizes power saving over rendering performance.
    • +
    +
  • +
  • premultipliedAlpha: Boolean that indicates that the page compositor will assume the drawing buffer contains colors with pre-multiplied alpha.
  • +
  • preserveDrawingBuffer: If the value is true the buffers will not be cleared and will preserve their values until cleared or overwritten by the author.
  • +
  • stencil: Boolean that indicates that the drawing buffer has a stencil buffer of at least 8 bits.
  • +
+
+
+ +

Return value

+ +

A {{domxref("RenderingContext")}} which is either a

+ + + +

If the contextType doesn't match a possible drawing context, null is returned.

+ +

Examples

+ +

Given this {{HTMLElement("canvas")}} element:

+ +
<canvas id="canvas" width="300" height="300"></canvas>
+
+ +

You can get a 2d context of the canvas with the following code:

+ +
var canvas = document.getElementById('canvas');
+var ctx = canvas.getContext('2d');
+console.log(ctx); // CanvasRenderingContext2D { ... }
+
+ +

Now you have the 2D rendering context for a canvas and you can draw within it.

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "scripting.html#dom-canvas-getcontext", "HTMLCanvasElement.getContext")}}{{Spec2('HTML WHATWG')}}No change since the latest snapshot, {{SpecName('HTML5 W3C')}}
{{SpecName('HTML5.1', "semantics-scripting.html#dom-htmlcanvaselement-getcontext", "HTMLCanvasElement.getContext")}}{{Spec2('HTML5.1')}}
{{SpecName('HTML5 W3C', "scripting-1.html#dom-canvas-getcontext", "HTMLCanvasElement.getContext")}}{{Spec2('HTML5 W3C')}}Snapshot of the {{SpecName('HTML WHATWG')}} containing the initial definition.
+ +

Browser compatibility

+ + + +

{{Compat("api.HTMLCanvasElement.getContext")}}

+ +

See also

+ + diff --git a/files/vi/web/api/htmlcanvaselement/index.html b/files/vi/web/api/htmlcanvaselement/index.html new file mode 100644 index 0000000000..50b2592322 --- /dev/null +++ b/files/vi/web/api/htmlcanvaselement/index.html @@ -0,0 +1,114 @@ +--- +title: HTMLCanvasElement +slug: Web/API/HTMLCanvasElement +tags: + - API + - Canvas + - HTML DOM + - Interface + - NeedsTranslation + - Reference + - TopicStub +translation_of: Web/API/HTMLCanvasElement +--- +
+
{{APIRef("Canvas API")}}
+
+ +

The HTMLCanvasElement interface provides properties and methods for manipulating the layout and presentation of {{HtmlElement("canvas")}} elements. The HTMLCanvasElement interface also inherits the properties and methods of the {{domxref("HTMLElement")}} interface.

+ +

{{InheritanceDiagram(600, 120)}}

+ +

Properties

+ +

Inherits properties from its parent, {{domxref("HTMLElement")}}.

+ +
+
{{domxref("HTMLCanvasElement.height")}}
+
Is a positive integer reflecting the {{htmlattrxref("height", "canvas")}} HTML attribute of the {{HTMLElement("canvas")}} element interpreted in CSS pixels. When the attribute is not specified, or if it is set to an invalid value, like a negative, the default value of 150 is used.
+
{{domxref("HTMLCanvasElement.width")}}
+
Is a positive integer reflecting the {{htmlattrxref("width", "canvas")}} HTML attribute of the {{HTMLElement("canvas")}} element interpreted in CSS pixels. When the attribute is not specified, or if it is set to an invalid value, like a negative, the default value of 300 is used.
+
{{domxref("HTMLCanvasElement.mozOpaque")}} {{non-standard_inline}} {{deprecated_inline}}
+
Is a {{jsxref("Boolean")}} reflecting the {{htmlattrxref("moz-opaque", "canvas")}} HTML attribute of the {{HTMLElement("canvas")}} element. It lets the canvas know whether or not translucency will be a factor. If the canvas knows there's no translucency, painting performance can be optimized. This is only supported in Mozilla-based browsers; use the standardized {{domxref("HTMLCanvasElement.getContext()", "canvas.getContext('2d', { alpha: false })")}} instead.
+
{{domxref("HTMLCanvasElement.mozPrintCallback")}}{{non-standard_inline}}
+
Is a function that is Initially null. Web content can set this to a JavaScript function that will be called when the canvas is to be redrawn while the page is being printed. When called, the callback is passed a "printState" object that implements the MozCanvasPrintState interface. The callback can get the context to draw to from the printState object and must then call done() on it when finished. The purpose of mozPrintCallback is to obtain a higher resolution rendering of the canvas at the resolution of the printer being used. See this blog post.
+
+ +

Methods

+ +

Inherits methods from its parent, {{domxref("HTMLElement")}}.

+ +
+
{{domxref("HTMLCanvasElement.captureStream()")}} {{experimental_inline}}
+
Returns a {{domxref("CanvasCaptureMediaStream")}} that is a real-time video capture of the surface of the canvas.
+
{{domxref("HTMLCanvasElement.getContext()")}}
+
Returns a drawing context on the canvas, or null if the context ID is not supported. A drawing context lets you draw on the canvas. Calling getContext with "2d" returns a {{domxref("CanvasRenderingContext2D")}} object, whereas calling it with "webgl" (or "experimental-webgl") returns a {{domxref("WebGLRenderingContext")}} object. This context is only available on browsers that implement WebGL.
+
{{domxref("HTMLCanvasElement.toDataURL()")}}
+
Returns a data-URL containing a representation of the image in the format specified by the type parameter (defaults to png). The returned image is in a resolution of 96dpi.
+
{{domxref("HTMLCanvasElement.toBlob()")}}
+
Creates a {{domxref("Blob")}} object representing the image contained in the canvas; this file may be cached on the disk or stored in memory at the discretion of the user agent.
+
{{domxref("HTMLCanvasElement.transferControlToOffscreen()")}} {{experimental_inline}}
+
Transfers control to an {{domxref("OffscreenCanvas")}} object, either on the main thread or on a worker.
+
{{domxref("HTMLCanvasElement.mozGetAsFile()")}} {{non-standard_inline}} {{deprecated_inline}}
+
Returns a {{domxref("File")}} object representing the image contained in the canvas; this file is a memory-based file, with the specified name. If type is not specified, the image type is image/png.
+
+ +

Events

+ +

Listen to these events using addEventListener().

+ +
+
webglcontextcreationerror
+
Fired if the user agent is unable to create a WebGLRenderingContext or WebGL2RenderingContext context.
+
webglcontextlost
+
Fired if the user agent detects that the drawing buffer associated with a WebGLRenderingContext or WebGL2RenderingContext object has been lost.
+
webglcontextrestored
+
Fired if the user agent restores the drawing buffer for a WebGLRenderingContext or WebGL2RenderingContext object.
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Media Capture DOM Elements', '#html-media-element-media-capture-extensions', 'HTMLCanvasElement')}}{{Spec2('Media Capture DOM Elements')}}Adds the method captureStream().
{{SpecName('HTML WHATWG', "#htmlcanvaselement", "HTMLCanvasElement")}}{{Spec2('HTML WHATWG')}}The method getContext() now returns a {{domxref("RenderingContext")}} rather than an opaque object.
+ The transferControlToOffscreen()method has been added.
{{SpecName('HTML5.1', "scripting-1.html#the-canvas-element", "HTMLCanvasElement")}}{{Spec2('HTML5.1')}} 
{{SpecName('HTML5 W3C', "scripting-1.html#the-canvas-element", "HTMLCanvasElement")}}{{Spec2('HTML5 W3C')}}Initial definition.
+ +

Browser compatibility

+ +
+ + +

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

+
+ +

See also

+ + diff --git a/files/vi/web/api/htmlelement/dataset/index.html b/files/vi/web/api/htmlelement/dataset/index.html new file mode 100644 index 0000000000..44ce2c7393 --- /dev/null +++ b/files/vi/web/api/htmlelement/dataset/index.html @@ -0,0 +1,139 @@ +--- +title: HTMLElement.dataset +slug: Web/API/HTMLElement/dataset +tags: + - API + - HTML DOM + - HTMLElement + - Tham khảo + - Thuộc tính + - dataset +translation_of: Web/API/HTMLOrForeignElement/dataset +--- +
{{ APIRef("HTML DOM") }}
+ +

The dataset property on the {{domxref("HTMLElement")}} interface provides read/write access to all the custom data attributes (data-*) set on the element. This access is available both in HTML and within the DOM.  It is a map of DOMString, one entry for each custom data attribute.  Note that the dataset property itself can be read, but not directly written.  Instead, all writes must be to the individual properties within the dataset, which in turn represent the data attributes.   Note also that an HTML data-attribute and its corresponding DOM dataset.property do not share the same name, but they are always similar:

+ + + +

In addition to the information below, you'll find a how-to guide for using HTML data attributes in our article Using data attributes.

+ +

Chuyển đổi tên

+ +

Từ dash-style (kiểu-gạch-nối) sang camelCase (bướuLạcĐà): Tên thuộc tính dữ liệu tùy biến được chuyển đổi thành khóa cho {{ domxref("DOMStringMap") }} dự trên quy định sau:

+ + + +

Từ camelCase (bướuLạcĐà) sang dash-style (kiểu-gạch-nối): Cách chuyển đổi ngược lại, dò theo khóa để tìm ra tên thuộc tính, bằng quy định sau:

+ + + +

Việc có rằng buộc trong quy định trên nhằm đảm bảo việc chuyển đổi có thể đảo ngược cho nhau.

+ +

Ví dụ, thuộc tính có tên data-abc-def sẽ có khóa tương ứng abcDef.

+ + + +

Truy cập giá trị

+ + + +

Loại giá trị

+ + + +

Cú pháp

+ + + +

Ví dụ

+ +
<div id="user" data-id="1234567890" data-user="johndoe" data-date-of-birth>John Doe</div>
+ +
const el = document.querySelector('#user');
+
+// el.id == 'user'
+// el.dataset.id === '1234567890'
+// el.dataset.user === 'johndoe'
+// el.dataset.dateOfBirth === ''
+
+// gán dữ liệu cho thuộc tính data
+el.dataset.dateOfBirth = '1960-10-03';
+// Kết quả: el.dataset.dateOfBirth === 1960-10-03
+
+delete el.dataset.dateOfBirth;
+// Kết quả: el.dataset.dateOfBirth === undefined
+
+// 'someDataAttr' in el.dataset === false
+el.dataset.someDataAttr = 'mydata';
+// Kết quả: 'someDataAttr' in el.dataset === true
+
+ +

Thông số kỹ thuật

+ + + + + + + + + + + + + + + + + + + + + + + + +
Thông số kỹ thuậtTrạng tháiChú thích
{{SpecName('HTML WHATWG', "dom.html#dom-dataset", "HTMLElement.dataset")}}{{Spec2('HTML WHATWG')}}No change from latest snapshot, {{SpecName('HTML5.1')}}
{{SpecName('HTML5.1', "dom.html#dom-dataset", "HTMLElement.dataset")}}{{Spec2('HTML5.1')}}Snapshot of {{SpecName('HTML WHATWG')}}, no change from {{SpecName('HTML5 W3C')}}
{{SpecName('HTML5 W3C', "dom.html#dom-dataset", "HTMLElement.dataset")}}{{Spec2('HTML5 W3C')}}Snapshot of  {{SpecName('HTML WHATWG')}}, initial definition.
+ +

Tính tương thích trên trình duyệt

+ + + +

{{Compat("api.HTMLElement.dataset")}}

+ +

Xem thêm

+ + diff --git a/files/vi/web/api/htmlelement/index.html b/files/vi/web/api/htmlelement/index.html new file mode 100644 index 0000000000..1a625a2a5b --- /dev/null +++ b/files/vi/web/api/htmlelement/index.html @@ -0,0 +1,268 @@ +--- +title: HTMLElement +slug: Web/API/HTMLElement +tags: + - API + - HTML DOM + - Interface +translation_of: Web/API/HTMLElement +--- +
{{ APIRef("HTML DOM") }}
+ +

Interface HTMLElement đại diện cho mọi phần tử HTML. Một vài phần tử sử dụng trực tiếp interface này, một vài phần tử khác lại sử dụng nó thông qua các lớp khác kế thừa nó.

+ +

{{InheritanceDiagram}}

+ +

Các thuộc tính

+ +

Được kế thừa từ {{domxref("Element")}}, và sử dụng chúng từ {{domxref("GlobalEventHandlers")}} và {{domxref("TouchEventHandlers")}}.

+ +
+
{{domxref("HTMLElement.accessKey")}}
+
Là một {{domxref("DOMString")}} trả về từ khoá truy cập được gán cho phần tử.
+
{{domxref("HTMLElement.accessKeyLabel")}} {{readonlyInline}}
+
Trả về một {{domxref("DOMString")}} chứa các từ khoá truy cập đã được gán của phần tử.
+
{{domxref("HTMLElement.contentEditable")}}
+
Là một {{domxref("DOMString")}}, nếu giá trị là "true", ta có thể chỉnh sửa phần tử này và ngược lại nếu giá trị là "false".
+
{{domxref("HTMLElement.isContentEditable")}} {{readonlyInline}}
+
Trả về giá trị {{domxref("Boolean")}} cho biết nội dung của phần tử có được phép chỉnh sửa hay không.
+
{{domxref("HTMLElement.contextMenu")}} {{deprecated_inline}}
+
Là một {{domxref("HTMLMenuElement")}} trả về một menu tóm lược liên kết các phần tử. Giá trị có thể là null.
+
{{domxref("HTMLElement.dataset")}} {{readonlyInline}}
+
Trả về một {{domxref("DOMStringMap")}} cho phép ta thao tác với các thuộc tính dữ liệu tùy biến của phần tử (data-*) .
+
{{domxref("HTMLElement.dir")}}
+
Là một {{domxref("DOMString")}}, tương tự với thuộc tính global dir, đại diện cho hướng hiển thị của phần tử. Các giá trị cho phép là "ltr", "rtl", và "auto".
+
{{domxref("HTMLElement.draggable")}}
+
Có kiểu {{jsxref("Boolean")}} cho ta biết phần tử có thể được kéo (drag) hay không.
+
{{domxref("HTMLElement.dropzone")}} {{readonlyInline}}
+
Trả về một {{domxref("DOMSettableTokenList")}} tương tự với thuộc tính global dropzone mô tả hành vi của phần tử liên quan đến hành động thả (drop).
+
{{domxref("HTMLElement.hidden")}}
+
Có kiểu {{jsxref("Boolean")}} cho ta biết phần tử có ẩn hay không.
+
{{domxref("HTMLElement.inert")}}
+
Có kiểu {{jsxref("Boolean")}} cho ta biết user agent must act as though the given node is absent đối với các sự kiện tương tác của người dùng, tìm kiếm văn bản trong trang, và lựa chọn văn bản.
+
{{domxref("HTMLElement.innerText")}}
+
Trả về nội dung văn bản được "render" từ một node và phần tử con của nó. Điều này tương tự với việc người dùng bôi đen văn bản và sao chép chúng.
+
{{domxref("HTMLElement.itemScope")}} {{experimental_inline}}
+
Có kiểu {{jsxref("Boolean")}} cho biết scope của item.
+
{{domxref("HTMLElement.itemType")}} {{readonlyInline}}{{experimental_inline}}
+
Trả về một {{domxref("DOMSettableTokenList")}}…
+
{{domxref("HTMLElement.itemId")}} {{experimental_inline}}
+
Là một {{domxref("DOMString")}} cho biết ID của item.
+
{{domxref("HTMLElement.itemRef")}} {{readonlyInline}}{{experimental_inline}}
+
Là một {{domxref("DOMSettableTokenList")}}…
+
{{domxref("HTMLElement.itemProp")}} {{readonlyInline}}{{experimental_inline}}
+
Trả về một {{domxref("DOMSettableTokenList")}}…
+
{{domxref("HTMLElement.itemValue")}} {{experimental_inline}}
+
Trả về một {{jsxref("Object")}} cho biết giá trị của item.
+
{{domxref("HTMLElement.lang")}}
+
Là một {{domxref("DOMString")}} cho biết ngôn ngữ của thuộc tính của một phần tử, của văn bản và của nội dung phần tử đó.
+
{{domxref("HTMLElement.noModule")}}
+
Có kiểu {{jsxref("Boolean")}} cho biết rằng việc nhúng đoạn script có thể được thực thi bởi user agent (có hỗ trợ module scripts) hay không.
+
{{domxref("HTMLElement.nonce")}}
+
Returns the cryptographic number used once that is used by Content Security Policy to determine whether a given fetch will be allowed to proceed.
+
{{domxref("HTMLElement.offsetHeight")}} {{readonlyInline}}{{experimental_inline}}
+
Returns a double containing the height of an element, relative to the layout.
+
{{domxref("HTMLElement.offsetLeft")}}{{readonlyInline}}{{experimental_inline}}
+
Returns a double, the distance from this element's left border to its offsetParent's left border.
+
{{domxref("HTMLElement.offsetParent")}}{{readonlyInline}}{{experimental_inline}}
+
Returns a {{domxref("Element")}} that is the element from which all offset calculations are currently computed.
+
{{domxref("HTMLElement.offsetTop")}}{{readonlyInline}}{{experimental_inline}}
+
Returns a double, the distance from this element's top border to its offsetParent's top border.
+
{{domxref("HTMLElement.offsetWidth")}}{{readonlyInline}}{{experimental_inline}}
+
Returns a double containing the width of an element, relative to the layout.
+
{{domxref("HTMLElement.properties")}} {{readonlyInline}}{{experimental_inline}}
+
Returns a {{domxref("HTMLPropertiesCollection")}}…
+
{{domxref("HTMLElement.spellcheck")}}{{ gecko_minversion_inline("1.9")}}
+
Is a {{jsxref("Boolean")}} that controls spell-checking. It is present on all HTML elements, though it doesn't have an effect on all of them.
+
{{domxref("HTMLElement.style")}}
+
Is a {{domxref("CSSStyleDeclaration")}}, an object representing the declarations of an element's style attributes.
+
{{domxref("HTMLElement.tabIndex")}}
+
Is a long representing the position of the element in the tabbing order.
+
{{domxref("HTMLElement.title")}}
+
Is a {{domxref("DOMString")}} containing the text that appears in a popup box when mouse is over the element.
+
{{domxref("HTMLElement.translate")}} {{experimental_inline}}
+
Is a {{jsxref("Boolean")}} representing the translation.
+
+ +

Event handlers

+ +

Most event handler properties, of the form onXYZ, are defined on the {{domxref("GlobalEventHandlers")}} or {{domxref("TouchEventHandlers")}} interfaces and implemented by HTMLElement. In addition, the following handlers are specific to HTMLElement.

+ +
+
{{ domxref("HTMLElement.oncopy") }} {{ non-standard_inline() }}
+
Returns the event handling code for the copy event ({{bug("280959")}}).
+
{{ domxref("HTMLElement.oncut") }} {{ non-standard_inline() }}
+
Returns the event handling code for the cut event ({{bug("280959")}}).
+
{{ domxref("HTMLElement.onpaste") }} {{ non-standard_inline() }}
+
Returns the event handling code for the paste event ({{bug("280959")}}).
+
{{domxref("TouchEventHandlers.ontouchstart")}} {{non-standard_inline}}
+
Returns the event handling code for the {{event("touchstart")}} event.
+
{{domxref("TouchEventHandlers.ontouchend")}} {{non-standard_inline}}
+
Returns the event handling code for the {{event("touchend")}} event.
+
{{domxref("TouchEventHandlers.ontouchmove")}} {{non-standard_inline}}
+
Returns the event handling code for the {{event("touchmove")}} event.
+
{{domxref("TouchEventHandlers.ontouchenter")}} {{non-standard_inline}}
+
Returns the event handling code for the {{event("touchenter")}} event.
+
{{domxref("TouchEventHandlers.ontouchleave")}} {{non-standard_inline}}
+
Returns the event handling code for the {{event("touchleave")}} event.
+
{{domxref("TouchEventHandlers.ontouchcancel")}} {{non-standard_inline}}
+
Returns the event handling code for the {{event("touchcancel")}} event.
+
+ +

Các phương thức

+ +

Được kế thừa từ {{domxref("Element")}}.

+ +
+
{{domxref("HTMLElement.blur()")}}
+
Bỏ truy cập phần tử hiện tại.
+
{{domxref("HTMLElement.click()")}}
+
Gửi một sự kiện click chuột đến phần tử.
+
{{domxref("HTMLElement.focus()")}}
+
Truy cập đến phần tử hiện tại (truy cập bằng cách click vào phần tử hoặc nhấn phím Tab để di chuyển đến).
+
{{domxref("HTMLElement.forceSpellCheck()")}} {{experimental_inline}}
+
Kiểm tra chính tả nội dung của phần tử.
+
+ +

Các sự kiện

+ +

Bắt các sự kiện bằng cách sự dụng phương thức addEventListener() hoặc bằng cách gán một thuộc tính sự sự kiện on_tên_sự_kiện dựa trên interface này.

+ +
+
invalid
+
Được gọi khi một phần tử không thỏa điều kiện khi đang xác minh (validation) thông tin.
+ Dùng tương tự với thuộc tính oninvalid.
+
+ +

Các sự kiện animation

+ +
+
animationcancel
+
Được gọi khi một animation dừng đột ngột.
+ Dùng tương tự với thuộc tính onanimationcancel.
+
animationend
+
Được gọi khi một animation kết thúc.
+ Dùng tương tự với thuộc tính onanimationend.
+
animationiteration
+
Được gọi khi một vòng lặp animation kết thúc.
+ Dùng tương tự với thuộc tính onanimationiteration.
+
animationstart
+
Fired when an animation starts.
+ Dùng tương tự với thuộc tính onanimationstart.
+
+ +

Các sự kiện input

+ +
+
beforeinput
+
Được gọi khi giá trị của một phần tử {{HTMLElement("input")}}, {{HTMLElement("select")}}, hoặc {{HTMLElement("textarea")}} sắp được chỉnh sửa.
+
input
+
Được gọi khi giá trị của một phần tử {{HTMLElement("input")}}, {{HTMLElement("select")}}, hoặc {{HTMLElement("textarea")}} đã được chỉnh sửa.
+ Dùng tương tự với thuộc tính oninput.
+
+ +

Pointer events

+ +
+
gotpointercapture
+
Fired when an element captures a pointer using setPointerCapture().
+ Also available via the ongotpointercapture property.
+
lostpointercapture
+
Fired when a captured pointer is released.
+ Also available via the onlostpointercapture property.
+
pointercancel
+
Fired when a pointer event is canceled.
+ Also available via the onpointercancel property.
+
pointerdown
+
Fired when a pointer becomes active.
+ Also available via the onpointerdown property.
+
pointerenter
+
Fired when a pointer is moved into the hit test boundaries of an element or one of its descendants.
+ Also available via the onpointerenter property.
+
pointerleave
+
Fired when a pointer is moved out of the hit test boundaries of an element.
+ Also available via the onpointerleave property.
+
pointermove
+
Fired when a pointer changes coordinates.
+ Also available via the onpointermove property.
+
pointerout
+
Fired when a pointer is moved out of the hit test boundaries of an element (among other reasons).
+ Also available via the onpointerout property.
+
pointerover
+
Fired when a pointer is moved into an element's hit test boundaries.
+ Also available via the onpointerover property.
+
pointerup
+
Fired when a pointer is no longer active.
+ Also available via the onpointerup property.
+
+ +

Các sự kiện transition

+ +
+
transitioncancel
+
Được gọi khi một CSS transition bị hủy.
+ Dùng tương tự với thuộc tính ontransitioncancel.
+
transitionend
+
Được gọi khi một CSS transition hoàn thành.
+ Dùng tương tự với thuộc tính ontransitionend.
+
transitionrun
+
Được gọi khi một CSS transition được tạo ra đầu tiên.
+ Dùng tương tự với thuộc tính ontransitionrun.
+
transitionstart
+
Được gọi khi một CSS transition thực sự bắt đầu.
+ Dùng tương tự với thuộc tính ontransitionstart.
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSSOM View', '#extensions-to-the-htmlelement-interface', 'HTMLElement')}}{{Spec2('CSSOM View')}}Added the following properties: offsetParent, offsetTop, offsetLeft, offsetWidth, and offsetHeight.
{{SpecName('HTML WHATWG', 'elements.html#htmlelement', 'HTMLElement')}}{{Spec2('HTML WHATWG')}}Added the following properties: translate, itemScope, itemType, itemId, itemRef, itemProp, properties, and itemValue.
+ Added the following method: forceSpellcheck().
+ Moved the onXYZ attributes to the {{domxref("GlobalEventHandlers")}} interface and added an inheritance from it.
{{SpecName('HTML5 W3C', 'dom.html#htmlelement', 'HTMLElement')}}{{Spec2('HTML5 W3C')}}Added the following properties: dataset, hidden, tabindex, accessKey, accessKeyLabel, draggable, dropzone, contentEditable, isContentEditable, contextMenu, spellcheck, commandType, commandLabel, commandIcon, commandHidden, commandDisabled, commandChecked, style, and all the onXYZ properties.
+ Moved the id and className properties to the {{domxref("Element")}} interface.
{{SpecName('DOM2 HTML', 'html.html#ID-011100101', 'HTMLElement')}}{{Spec2('DOM2 HTML')}}No change from {{SpecName('DOM2 HTML')}}
{{SpecName('DOM1', 'level-one-html.html#ID-011100101', 'HTMLElement')}}{{Spec2('DOM1')}}Initial definition.
+ +

Khả năng tương thích của trình duyệt

+ + + +

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

+ +

Xem thêm

+ + diff --git a/files/vi/web/api/htmlformelement/index.html b/files/vi/web/api/htmlformelement/index.html new file mode 100644 index 0000000000..1df37a6657 --- /dev/null +++ b/files/vi/web/api/htmlformelement/index.html @@ -0,0 +1,246 @@ +--- +title: HTMLFormElement +slug: Web/API/HTMLFormElement +tags: + - API + - DOM + - Form Element + - Forms + - HTML + - HTML DOM + - HTML Form Element + - HTML forms + - HTMLFormElement + - Interface + - NeedsTranslation + - Reference + - TopicStub +translation_of: Web/API/HTMLFormElement +--- +
{{APIRef("HTML DOM")}}
+ +

The {{domxref("HTMLFormElement")}} interface represents a {{HTMLElement("form")}} element in the DOM; it allows access to and in some cases modification of aspects of the form, as well as access to its component elements.

+ +

{{InheritanceDiagram(600,120)}}

+ +

Properties

+ +

This interface also inherits properties from its parent, {{domxref("HTMLElement")}}.

+ +
+
{{domxref("HTMLFormElement.elements")}} {{ReadOnlyInline}}
+
A {{domxref("HTMLFormControlsCollection")}} holding all form controls belonging to this form element.
+
{{domxref("HTMLFormElement.length")}}{{ReadOnlyInline}}
+
A long reflecting  the number of controls in the form.
+
{{domxref("HTMLFormElement.name")}}
+
A {{domxref("DOMString")}} reflecting the value of the form's {{ htmlattrxref("name", "form") }} HTML attribute, containing the name of the form.
+
{{domxref("HTMLFormElement.method")}}
+
A {{domxref("DOMString")}} reflecting the value of the form's {{ htmlattrxref("method", "form") }} HTML attribute, indicating the HTTP method used to submit the form. Only specified values can be set.
+
{{domxref("HTMLFormElement.target")}}
+
A {{domxref("DOMString")}} reflecting the value of the form's {{ htmlattrxref("target", "form") }} HTML attribute, indicating where to display the results received from submitting the form.
+
{{domxref("HTMLFormElement.action")}}
+
A {{domxref("DOMString")}} reflecting the value of the form's {{ htmlattrxref("action", "form") }} HTML attribute, containing the URI of a program that processes the information submitted by the form.
+
{{domxref("HTMLFormElement.encoding")}} or {{domxref("HTMLFormElement.enctype")}}
+
A {{domxref("DOMString")}} reflecting the value of the form's {{ htmlattrxref("enctype", "form") }} HTML attribute, indicating the type of content that is used to transmit the form to the server. Only specified values can be set. The two properties are synonyms.
+
{{domxref("HTMLFormElement.acceptCharset")}}
+
A {{domxref("DOMString")}} reflecting the value of the form's {{ htmlattrxref("accept-charset", "form") }} HTML attribute, representing the character encoding that the server accepts.
+
{{domxref("HTMLFormElement.autocomplete")}}
+
A {{domxref("DOMString")}} reflecting the value of the form's {{ htmlattrxref("autocomplete", "form") }} HTML attribute, indicating whether the controls in this form can have their values automatically populated by the browser.
+
{{domxref("HTMLFormElement.noValidate")}}
+
A {{jsxref("Boolean")}} reflecting the value of the form's  {{ htmlattrxref("novalidate", "form") }} HTML attribute, indicating whether the form should not be validated.
+
+ +

Named inputs are added to their owner form instance as properties, and can overwrite native properties if they share the same name (eg a form with an input named action will have its action property return that input instead of the form's {{ htmlattrxref("action", "form") }} HTML attribute).

+ +

Methods

+ +

This interface also inherits methods from its parent, {{domxref("HTMLElement")}}.

+ +
+
{{domxref("HTMLFormElement.submit()")}}
+
Submits the form to the server.
+
{{domxref("HTMLFormElement.reset()")}}
+
Resets the form to its initial state.
+
{{domxref("HTMLFormElement.checkValidity()")}}
+
Returns true if the element's child controls are subject to constraint validation and satisfy those contraints; returns false if some controls do not satisfy their constraints. Fires an event named {{event("invalid")}} at any control that does not satisfy its constraints; such controls are considered invalid if the event is not canceled. It is up to the programmer to decide how to respond to false.
+
{{domxref("HTMLFormElement.reportValidity()")}}
+
Returns true if the element's child controls satisfy their validation constraints. When false is returned, cancelable {{Event("invalid")}} events are fired for each invalid child and validation problems are reported to the user.
+
{{domxref("HTMLFormElement.requestAutocomplete()")}} {{obsolete_inline}}
+
Triggers a native browser interface to assist the user in completing the fields which have an autofill field name value that is not off or on. The form will receive an event once the user has finished with the interface, the event will either be {{event("autocomplete")}} when the fields have been filled or {{event("autocompleteerror")}} when there was a problem. This method has been removed from Chrome and Firefox — see {{bug(1270740)}} for background information on why.
+
+ +

Events

+ +

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

+ +
+
reset
+
 The reset event fires when a form is reset.
+ Also available via the onreset property.
+
submit
+
The submit event fires when a form is submitted.
+ Also available via the onsubmit property.
+
+ +

Usage notes

+ +

Obtaining a form element object

+ +

To obtain an HTMLFormElement object, you can use a CSS selector with {{domxref("ParentNode.querySelector", "querySelector()")}}, or you can get a list of all of the forms in the document using its {{domxref("Document.forms", "forms")}} property.

+ +

{{domxref("Document.forms")}} returns an array of HTMLFormElement objects listing each of the forms on the page. You can then use any of the following syntaxes to get an individual form:

+ +
+
document.forms[index]
+
Returns the form at the specified index into the array of forms.
+
document.forms[id]
+
Returns the form whose ID is id.
+
document.forms[name]
+
Returns the form whose {{domxref("Element.name", "name")}} attribute's value is name.
+
+ +

Accessing the form's elements

+ +

You can access the list of the form's data-containing elements by examining the form's {{domxref("HTMLFormElement.elements", "elements")}} property. This returns an {{domxref("HTMLFormControlsCollection")}} listing all of the form's user data entry elements, both those which are descendants of the <form> and those which are made members of the form using their form attributes.

+ +

Elements that are considered form controls

+ +

The elements which are included by HTMLFormElement.elements and HTMLFormElement.length are:

+ + + +

No other elements are included in the list returned by elements, which makes it an excellent way to get at the elements most important when processing forms.

+ +

Examples

+ +

Creating a new form element, modifying its attributes, then submitting it:

+ +
var f = document.createElement("form");// Create a form
+document.body.appendChild(f);          // Add it to the document body
+f.action = "/cgi-bin/some.cgi";        // Add action and method attributes
+f.method = "POST";
+f.submit();                            // Call the form's submit method
+
+ +

Extract information from a form element and set some of its attributes:

+ +
<form name="formA" action="/cgi-bin/test" method="post">
+ <p>Press "Info" for form details, or "Set" to change those details.</p>
+ <p>
+  <button type="button" onclick="getFormInfo();">Info</button>
+  <button type="button" onclick="setFormInfo(this.form);">Set</button>
+  <button type="reset">Reset</button>
+ </p>
+
+ <textarea id="form-info" rows="15" cols="20"></textarea>
+</form>
+
+<script>
+  function getFormInfo(){
+    // Get a reference to the form via its name
+    var f = document.forms["formA"];
+    // The form properties we're interested in
+    var properties = [ 'elements', 'length', 'name', 'charset', 'action', 'acceptCharset', 'action', 'enctype', 'method', 'target' ];
+    // Iterate over the properties, turning them into a string that we can display to the user
+    var info = properties.map(function(property) { return property + ": " + f[property] }).join("\n");
+
+    // Set the form's <textarea> to display the form's properties
+    document.forms["formA"].elements['form-info'].value = info;
+  }
+
+  function setFormInfo(f){ // Argument should be a form element reference.
+    f.action = "a-different-url.cgi";
+    f.name   = "a-different-name";
+  }
+</script>
+
+ +

Submit a form into a new window:

+ +
<!doctype html>
+<html>
+<head>
+<meta charset="utf-8">
+<title>Example new-window form submission</title>
+</head>
+<body>
+
+<form action="test.php" target="_blank">
+  <p><label>First name: <input type="text" name="firstname"></label></p>
+  <p><label>Last name: <input type="text" name="lastname"></label></p>
+  <p><label><input type="password" name="pwd"></label></p>
+
+  <fieldset>
+   <legend>Pet preference</legend>
+    <p><label><input type="radio" name="pet" value="cat"> Cat</label></p>
+    <p><label><input type="radio" name="pet" value="dog"> Dog</label></p>
+  </fieldset>
+
+  <fieldset>
+    <legend>Owned vehicles</legend>
+
+    <p><label><input type="checkbox" name="vehicle" value="Bike">I have a bike</label></p>
+    <p><label><input type="checkbox" name="vehicle" value="Car">I have a car</label></p>
+  </fieldset>
+
+  <p><button>Submit</button></p>
+</form>
+
+</body>
+</html>
+ +

Submitting forms and uploading files using XMLHttpRequest

+ +

If you want to know how to serialize and submit a form using the {{domxref("XMLHttpRequest")}} API, please read this paragraph.

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "#htmlformelement", "HTMLFormElement")}}{{Spec2('HTML WHATWG')}}The following method has been added: requestAutocomplete().
{{SpecName('HTML5 W3C', "forms.html#the-form-element", "HTMLFormElement")}}{{Spec2('HTML5 W3C')}}The elements properties returns an {{domxref("HTMLFormControlsCollection")}} instead of a raw {{domxref("HTMLCollection")}}. This is mainly a technical change. The following method has been added: checkValidity(). The following properties have been added: autocomplete, noValidate, and encoding.
{{SpecName('DOM2 HTML', 'html.html#ID-40002357', 'HTMLFormElement')}}{{Spec2('DOM2 HTML')}}No change
{{SpecName('DOM1', 'level-one-html.html#ID-40002357', 'HTMLFormElement')}}{{Spec2('DOM1')}}Initial definition
+ +

Browser compatibility

+ + + +

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

+ +

See also

+ + diff --git a/files/vi/web/api/htmlformelement/reset/index.html b/files/vi/web/api/htmlformelement/reset/index.html new file mode 100644 index 0000000000..dc68298cab --- /dev/null +++ b/files/vi/web/api/htmlformelement/reset/index.html @@ -0,0 +1,28 @@ +--- +title: HTMLFormElement.reset() +slug: Web/API/HTMLFormElement/reset +translation_of: Web/API/HTMLFormElement/reset +--- +
{{APIRef("HTML DOM")}}
+ +

Phương thức HTMLFormEuity.reset () khôi phục các giá trị mặc định của thành phần biểu mẫu. Phương pháp này thực hiện tương tự như nhấp vào nút đặt lại của biểu mẫu

+ +

Nếu một điều khiển biểu mẫu (chẳng hạn như nút đặt lại) có tên hoặc id của thiết lập lại, nó sẽ che dấu phương thức đặt lại của biểu mẫu. Nó không thiết lập lại các thuộc tính khác trong đầu vào, chẳng hạn như bị vô hiệu hóa.

+ +

Syntax

+ +
HTMLFormElement.reset()
+
+ +

Example

+ +
document.getElementById('myform').reset();
+
+ +

Specification

+ +

Browser compatibility

+ + + +

{{Compat("api.HTMLFormElement.reset")}}

diff --git a/files/vi/web/api/index.html b/files/vi/web/api/index.html new file mode 100644 index 0000000000..71e6573815 --- /dev/null +++ b/files/vi/web/api/index.html @@ -0,0 +1,34 @@ +--- +title: Web API Interfaces +slug: Web/API +tags: + - API + - Apps + - JavaScript + - NeedsTranslation + - Reference + - TopicStub + - Web +translation_of: Web/API +--- +

Có rất nhiều API tốt khi viết Web bằng Javascript. Dưới đây là danh sách những interfaces (những kiểu object) mà bạn có thể sử dụng khi phát triển Web app hay Website.

+ +

Web APIs thường được viết bởi JavaScript, nhưng không phải luôn là như vậy.

+ +

Đặc tả

+ +

Đây là danh sách tất cả những API sẵn có.

+ +
{{ListGroups}}
+ +

Interfaces

+ +

Đây là danh sách tất cả những interfaces (những kiểu object) sẵn có.

+ +
{{APIListAlpha}}
+ +

Xem thêm

+ + diff --git a/files/vi/web/api/navigator/geolocation/index.html b/files/vi/web/api/navigator/geolocation/index.html new file mode 100644 index 0000000000..4881071171 --- /dev/null +++ b/files/vi/web/api/navigator/geolocation/index.html @@ -0,0 +1,53 @@ +--- +title: Navigator.geolocation +slug: Web/API/Navigator/geolocation +tags: + - API + - Bất động sản + - Geolocation API + - Tham khảo +translation_of: Web/API/Navigator/geolocation +--- +
{{securecontext_header}}{{APIRef("Geolocation API")}}
+ +

Navigator.geolocation với đặc tính chỉ cho đọc trả lại một đối tượng {{domxref("Geolocation")}} cho phép trang web truy cập thông tin địa điểm của thiết bị. Việc này cho phép trang web hoặc phần mềm đưa ra đề nghị chào hàng dựa trên vị trí của người dùng.

+ +
+

Ghi chú: Vì lý do bảo mật, khi một trang web cố gắng truy cập vị trí, người dùng sẽ được thông báo và hỏi cấp yêu cầu cho phép. Hãy cẩn thận vì mỗi trình duyệt web có chính sách và phương pháp khác nhau.

+
+ +

Syntax

+ +
geo = navigator.geolocation
+
+ +

Specifications

+ + + + + + + + + + + + + + + + +
Chi tiết kỹ thuậtTình trạngGhi chú
{{SpecName('Geolocation', '#navi-geo', 'Navigator.geolocation')}}{{Spec2('Geolocation')}}Initial definition
+ +

Tương thích vơi trình duyệt

+ + + +

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

+ +

Xem thêm

+ + diff --git a/files/vi/web/api/navigator/index.html b/files/vi/web/api/navigator/index.html new file mode 100644 index 0000000000..e9ab7a7b29 --- /dev/null +++ b/files/vi/web/api/navigator/index.html @@ -0,0 +1,186 @@ +--- +title: Navigator +slug: Web/API/Navigator +tags: + - API + - DOM4 + - Interface + - Navigator + - NeedsTranslation + - Reference + - TopicStub + - Web + - Web Performance +translation_of: Web/API/Navigator +--- +
{{APIRef("DOM4")}}
+ +

The Navigator interface represents the state and the identity of the user agent. It allows scripts to query it and to register themselves to carry on some activities.

+ +

A Navigator object can be retrieved using the read-only {{domxref("window.navigator")}} property.

+ +

Properties

+ +

Doesn't inherit any properties, but implements those defined in {{domxref("NavigatorID")}}, {{domxref("NavigatorLanguage")}}, {{domxref("NavigatorOnLine")}}, {{domxref("NavigatorContentUtils")}}, {{domxref("NavigatorStorage")}}, {{domxref("NavigatorStorageUtils")}}, {{domxref("NavigatorConcurrentHardware")}}, {{domxref("NavigatorPlugins")}}, and {{domxref("NavigatorUserMedia")}}.

+ +

Standard

+ +
+
{{domxref("Navigator.activeVRDisplays")}} {{readonlyInline}}{{experimental_inline}}
+
Returns an array containing every {{domxref("VRDisplay")}} object that is currently presenting ({{domxref("VRDisplay.ispresenting")}} is true).
+
{{domxref("NavigatorID.appCodeName")}} {{readonlyInline}}{{experimental_inline}}
+
Returns the internal "code" name of the current browser. Do not rely on this property to return the correct value.
+
{{domxref("NavigatorID.appName")}} {{readonlyInline}}{{experimental_inline}}
+
Returns a {{domxref("DOMString")}} with the official name of the browser. Do not rely on this property to return the correct value.
+
{{domxref("NavigatorID.appVersion")}} {{readonlyInline}}{{experimental_inline}}
+
Returns the version of the browser as a {{domxref("DOMString")}}. Do not rely on this property to return the correct value.
+
{{domxref("Navigator.battery")}} {{readonlyInline}}
+
Returns a {{domxref("BatteryManager")}} object you can use to get information about the battery charging status.
+
{{domxref("Navigator.connection")}} {{readonlyInline}}{{experimental_inline}}
+
Provides a {{domxref("NetworkInformation")}} object containing information about the network connection of a device.
+
{{domxref("Navigator.cookieEnabled")}} {{readonlyinline}}
+
Returns false if setting a cookie will be ignored and true otherwise.
+
{{domxref("Navigator.geolocation")}} {{readonlyInline}}
+
Returns a {{domxref("Geolocation")}} object allowing accessing the location of the device.
+
{{domxref("NavigatorConcurrentHardware.hardwareConcurrency")}} {{readOnlyInline}}
+
Returns the number of logical processor cores available.
+
{{domxref("NavigatorPlugins.javaEnabled")}} {{readonlyInline}}{{experimental_inline}}
+
Returns a {{domxref("Boolean")}} flag indicating whether the host browser is Java-enabled or not.
+
{{domxref('Navigator.keyboard')}} {{readonlyinline}} {{experimental_inline}}
+
Returns a {{domxref('Keyboard')}} object which provides access to functions that retrieve keyboard layout maps and toggle capturing of key presses from the physical keyboard.
+
{{domxref("NavigatorLanguage.language")}} {{readonlyInline}}
+
Returns a {{domxref("DOMString")}} representing the preferred language of the user, usually the language of the browser UI. The null value is returned when this is unknown.
+
{{domxref("NavigatorLanguage.languages")}} {{readonlyInline}}
+
Returns an array of {{domxref("DOMString")}} representing the languages known to the user, by order of preference.
+
{{domxref("Navigator.locks")}} {{readonlyinline}}{{experimental_inline}}
+
Returns a {{domxref("LockManager")}} object which provides methods for requesting a new {{domxref('Lock')}} object and querying for an existing {{domxref('Lock')}} object
+
{{domxref("Navigator.mediaCapabilities")}} {{readonlyinline}}{{experimental_inline}}
+
Returns a {{domxref("MediaCapabilities")}} object that can expose information about the decoding and encoding capabilities for a given format and output capabilities.
+
{{domxref("Navigator.maxTouchPoints")}} {{readonlyInline}}
+
Returns the maximum number of simultaneous touch contact points are supported by the current device.
+
{{domxref("NavigatorPlugins.mimeTypes")}} {{readonlyInline}}{{experimental_inline}}
+
Returns an {{domxref("MimeTypeArray")}} listing the MIME types supported by the browser.
+
{{domxref("NavigatorOnLine.onLine")}} {{readonlyInline}}
+
Returns a {{domxref("Boolean")}} indicating whether the browser is working online.
+
{{domxref("Navigator.oscpu")}}
+
Returns a string that represents the current operating system.
+
{{domxref("Navigator.permissions")}} {{readonlyinline}}{{experimental_inline}}
+
Returns a {{domxref("Permissions")}} object that can be used to query and update permission status of APIs covered by the Permissions API.
+
{{domxref("NavigatorID.platform")}} {{readonlyInline}}{{experimental_inline}}
+
Returns a string representing the platform of the browser. Do not rely on this function to return a significant value.
+
{{domxref("NavigatorPlugins.plugins")}} {{readonlyInline}}{{experimental_inline}}
+
Returns a {{domxref("PluginArray")}} listing the plugins installed in the browser.
+
{{domxref("NavigatorID.product")}} {{readonlyInline}} {{experimental_inline}}
+
Always returns 'Gecko', on any browser. This property is kept only for compatibility purpose.
+
{{domxref("Navigator.serviceWorker")}} {{readonlyInline}}
+
Returns a {{domxref("ServiceWorkerContainer")}} object, which provides access to registration, removal, upgrade, and communication with the {{domxref("ServiceWorker")}} objects for the associated document.
+
{{domxref("NavigatorStorage.storage")}} {{readonlyinline}}
+
Returns the singleton {{domxref('StorageManager')}} object used for managing persistence permissions and estimating available storage on a site-by-site/app-by-app basis.
+
{{domxref("NavigatorID.userAgent")}} {{readonlyInline}}
+
Returns the user agent string for the current browser.
+
{{domxref("Navigator.webdriver")}} {{readonlyInline}} {{experimental_inline}}
+
Indicates whether the user agent is controlled by automation.
+
+ +

Non-standard

+ +
+
{{domxref("Navigator.buildID")}} {{non-standard_inline}}
+
Returns the build identifier of the browser. In modern browsers this property now returns a fixed timestamp as a privacy measure, e.g. 20181001000000 in Firefox 64 onwards.
+
{{domxref("Navigator.credentials")}} {{non-standard_inline}}
+
Returns the {{domxref("CredentialsContainer")}} interface which exposes methods to request credentials and notify the user agent when interesting events occur such as successful sign in or sign out. 
+
{{domxref("Navigator.deviceMemory")}} {{readonlyInline}} {{non-standard_inline}}
+
Returns the amount of device memory in gigabytes. This value is an approximation given by rounding to the nearest power of 2 and dividing that number by 1024.
+
{{domxref("Navigator.doNotTrack")}} {{non-standard_inline}}
+
Reports the value of the user's do-not-track preference. When this value is "yes", your web site or application should not track the user.
+
{{domxref("Navigator.mediaDevices")}} {{non-standard_inline}}
+
Returns a reference to a {{domxref("MediaDevices")}} object which can then be used to get information about available media devices ({{domxref("MediaDevices.enumerateDevices()")}}), find out what constrainable properties are supported for media on the user's computer and user agent ({{domxref("MediaDevices.getSupportedConstraints()")}}), and to request access to media using {{domxref("MediaDevices.getUserMedia()")}}.
+
{{domxref("Navigator.mozNotification")}} {{obsolete_inline}} {{deprecated_inline("22")}} {{non-standard_inline}}
+ {{domxref("Navigator.webkitNotification")}} {{obsolete_inline}}
+
Returns a {{domxref("navigator.mozNotification", "notification")}} object you can use to deliver notifications to the user from your web application.
+
{{domxref("Navigator.mozSocial")}} {{non-standard_inline}}
+
The Object, returned by the navigator.mozSocial property, is available within the social media provider's panel to provide functionality it may need.
+
{{domxref("Navigator.presentation")}} {{non-standard_inline}}
+
Returns a reference to the {{domxref("Presentation")}} API.
+
{{domxref("Navigator.productSub")}} {{non-standard_inline}}
+
Returns the build number of the current browser (e.g., "20060909").
+
{{domxref("Navigator.securitypolicy")}} {{non-standard_inline}}
+
Returns an empty string. In Netscape 4.7x, returns "US & CA domestic policy" or "Export policy".
+
{{domxref("Navigator.standalone")}} {{non-standard_inline}}
+
Returns a boolean indicating whether the browser is running in standalone mode. Available on Apple's iOS Safari only.
+
{{domxref("Navigator.storageQuota")}} {{readonlyinline}} {{experimental_inline}}
+
Returns a {{domxref('StorageQuota')}} interface which provides means to query and request storage usage and quota information.
+
{{domxref("Navigator.vendor")}} {{non-standard_inline}}
+
Returns the vendor name of the current browser (e.g., "Netscape6").
+
{{domxref("Navigator.vendorSub")}} {{non-standard_inline}}
+
Returns the vendor version number (e.g. "6.1").
+
{{domxref("Navigator.webkitPointer")}} {{non-standard_inline}}
+
Returns a PointerLock object for the Mouse Lock API.
+
+ +

Methods

+ +

Doesn't inherit any method, but implements those defined in {{domxref("NavigatorID")}}, {{domxref("NavigatorContentUtils")}}, {{domxref("NavigatorUserMedia")}}, and {{domxref("NavigatorStorageUtils")}}.

+ +

Standard

+ +
+
{{domxref("Navigator.canShare()")}} {{experimental_inline}}
+
Returns true if a call to Navigator.share() would succeed.
+
{{domxref("Navigator.getVRDisplays()")}} {{experimental_inline}}
+
Returns a promise that resolves to an array of {{domxref("VRDisplay")}} objects representing any available VR devices connected to the computer.
+
{{domxref("Navigator.getUserMedia", "Navigator.getUserMedia()")}} {{experimental_inline}}
+
After having prompted the user for permission, returns the audio or video stream associated to a camera or microphone on the local computer.
+
{{domxref("Navigator.registerContentHandler()")}} {{Obsolete_inline(59)}}
+
Allows web sites to register themselves as a possible handler for a given MIME type.
+
{{domxref("Navigator.registerProtocolHandler()")}}
+
Allows web sites to register themselves as a possible handler for a given protocol.
+
{{domxref("Navigator.requestMediaKeySystemAccess()")}} {{experimental_inline}}
+
Returns a {{jsxref("Promise")}} for a MediaKeySystemAccess object.
+
{{domxref("Navigator.sendBeacon()")}}{{experimental_inline}}
+
Used to asynchronously transfer a small amount of data using {{Glossary("HTTP")}} from the User Agent to a web server.
+
{{domxref("Navigator.share()")}}{{experimental_inline}}
+
Invokes the native sharing mechanism of the current platform.
+
{{domxref("NavigatorID.taintEnabled()")}} {{deprecated_inline("1.7.8")}} {{obsolete_inline("9.0")}} {{experimental_inline}}
+
Returns false. JavaScript taint/untaint functions removed in JavaScript 1.2.
+
{{domxref("Navigator.vibrate()")}} {{gecko_minversion_inline("11.0")}}
+
Causes vibration on devices with support for it. Does nothing if vibration support isn't available.
+
+ +

Non-standard

+ +
+

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

+
+ +
+
{{domxref("Navigator.mozIsLocallyAvailable()")}} {{non-standard_inline}}
+
Lets code check to see if the document at a given URI is available without using the network.
+
{{domxref("Navigator.mozPay()")}} {{non-standard_inline}}
+
Allows in-app payment.
+
+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#the-navigator-object', 'the Navigator object')}}{{Spec2('HTML WHATWG')}}
+ +

Browser compatibility

+ + + +
{{Compat("api.Navigator")}}
diff --git a/files/vi/web/api/navigator/sendbeacon-vi/index.html b/files/vi/web/api/navigator/sendbeacon-vi/index.html new file mode 100644 index 0000000000..a91adf05fd --- /dev/null +++ b/files/vi/web/api/navigator/sendbeacon-vi/index.html @@ -0,0 +1,104 @@ +--- +title: Navigator.sendBeacon() +slug: Web/API/Navigator/sendBeacon-vi +tags: + - API + - Beacon + - Navigator + - sendBeacon + - web perfomance +translation_of: Web/API/Navigator/sendBeacon +--- +
Phương thức navigator.sendBeacon() gửi {{glossary("Asynchronous", "bất đồng bộ")}} 1 lượng nhỏ dữ liệu đến máy chủ (web server) thông qua giao thức {{Glossary("HTTP")}} .
+ +

Cú pháp

+ +
navigator.sendBeacon(url, data);
+
+ +

Tham Số

+ +
+
url
+
Đường dẫn để nhận dữ liệu (Tạo request). Có thể là đường dẫn tuyệt đối hoặc tương đối.
+
data
+
Một đối tượng chứa dữ liệu để gửi đi có thể là 1 {{domxref("ArrayBuffer")}}, {{domxref("ArrayBufferView")}}, {{domxref("Blob")}}, {{domxref("DOMString")}}, {{domxref("FormData")}}, hoặc {{domxref("URLSearchParams")}}.
+
+ +

Giá trị trả về

+ +

Phương thức sendBeacon() trả về true nếu như {{glossary("user agent")}} (tác nhân người dùng hay web browser) xếp dữ liệu (data) để gửi đi thành công. Nếu không, sẽ trả về false.

+ +

Mô tả

+ +

Phương thức này dùng cho phân tích và chuẩn đoán cần gửi dữ liệu về máy chủ trước thời điểm đóng trang, nếu như gửi sớm hơn, có thể sẽ bị thiếu thông tin cần thu thập. Ví dụ, đường dẫn nào người dùng nhấn vào trước khi chuyển đến trang khác và đóng trang.

+ +

Việc đảm bảo rằng dữ liệu được gửi đi trong khi đóng trang (unload) trước đây thường rất khó để thực hiện, bởi user agents (web browser) luôn bỏ qua những {{domxref("XMLHttpRequest")}} bất đồng bộ được chạy trong sự kiện {{domxref("Window/unload_event", "unload")}}.

+ +

Trước đây, người ta thường làm trễ thời gian tải lại trang đủ lâu để gửi được dữ liệu đi bằng 1 số cách sau:

+ + + +

Tất cả những phương thức đó đều chặn quá trình tải lại trang, làm chậm việc chuyển đến trang tiếp theo. Trang tiếp theo không thể làm gì để ngăn chặn việc này, vì vậy trang mới sẽ có vẻ chậm đi, mặc dù đó là lỗi từ trang trước.

+ +

Ví dụ sau đây là 1 đoạn code mẫu để gửi dữ liệu về server bằng 1 XMLHttpRequest đồng bộ trong khi xử lý unload. Điều này làm trễ việc tải trang tiếp theo.

+ +
window.addEventListener("unload", function logData() {
+  var xhr = new XMLHttpRequest();
+  xhr.open("POST", "/log", false); // tham số thứ 3 là `false` để gửi request bất đồng bộ
+  xhr.send(analyticsData);
+});
+
+ +

Đây là những gì sendBeacon() thay thế. Với phương thức sendBeacon(), dữ liệu sẽ được gửi đi bất đồng bộ, User Agent (trình duyệt) có thể làm thế mà không tạo trễ khi tải lại trang hoặc chuyển đến trang tiếp theo. Điều này giải quyết tất cả vấn đề với việc gửi các dữ liệu phân tích:

+ + + +

Ví dụ sau đây là 1 đoạn code mẫu để gửi dữ liệu về server sử dụng phương thức sendBeacon().

+ +
window.addEventListener("unload", function logData() {
+  navigator.sendBeacon("/log", analyticsData);
+});
+
+ +

sendBeacon tạo 1 HTTP request với phương thức POST, kèm theo tất cả cookies liên quan khi được gọi.

+ +

Tài liệu chi tiết

+ + + + + + + + + + + + + + + + +
Tài liệuTrạng tháiBình luận
{{SpecName('Beacon', '#sendbeacon-method', 'sendBeacon()')}}{{Spec2('Beacon')}}Định nghĩa đầu tiên
+ +

Tương thích với trình duyệt

+ + + +

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

+ +

Xem thêm

+ + diff --git a/files/vi/web/api/node/index.html b/files/vi/web/api/node/index.html new file mode 100644 index 0000000000..0d23b9445d --- /dev/null +++ b/files/vi/web/api/node/index.html @@ -0,0 +1,373 @@ +--- +title: Node +slug: Web/API/Node +tags: + - API + - DOM + - DOM Reference + - NeedsTranslation + - Reference + - TopicStub + - WebAPI +translation_of: Web/API/Node +--- +
{{APIRef("DOM")}}
+ +

A Node is an interface from which a number of DOM types inherit, and allows these various types to be treated (or tested) similarly.

+ +

The following interfaces all inherit from Node its methods and properties: {{domxref("Document")}}, {{domxref("Element")}}, {{domxref("CharacterData")}} (which {{domxref("Text")}}, {{domxref("Comment")}}, and {{domxref("CDATASection")}} inherit), {{domxref("ProcessingInstruction")}}, {{domxref("DocumentFragment")}}, {{domxref("DocumentType")}}, {{domxref("Notation")}}, {{domxref("Entity")}}, {{domxref("EntityReference")}}

+ +

These interfaces may return null in particular cases where the methods and properties are not relevant. They may throw an exception - for example when adding children to a node type for which no children can exist.

+ +

Properties

+ +

Inherits properties from its parents {{domxref("EventTarget")}}.[1]

+ +
+
{{domxref("Node.baseURI")}} {{readonlyInline}}
+
Returns a {{domxref("DOMString")}} representing the base URL. The concept of base URL changes from one language to another; in HTML, it corresponds to the protocol, the domain name and the directory structure, that is all until the last '/'.
+
{{domxref("Node.baseURIObject")}} {{Non-standard_inline()}} {{ Fx_minversion_inline("3") }}
+
(Not available to web content.) The read-only {{ Interface("nsIURI") }} object representing the base URI for the element.
+
{{domxref("Node.childNodes")}} {{readonlyInline}}
+
Returns a live {{domxref("NodeList")}} containing all the children of this node. {{domxref("NodeList")}} being live means that if the children of the Node change, the {{domxref("NodeList")}} object is automatically updated.
+
{{domxref("Node.firstChild")}} {{readonlyInline}}
+
Returns a {{domxref("Node")}} representing the first direct child node of the node, or null if the node has no child.
+
{{domxref("Node.lastChild")}} {{readonlyInline}}
+
Returns a {{domxref("Node")}} representing the last direct child node of the node, or null if the node has no child.
+
{{domxref("Node.localName")}} {{obsolete_inline}}{{readonlyInline}}
+
Returns a {{domxref("DOMString")}} representing the local part of the qualified name of an element. In Firefox 3.5 and earlier, the property upper-cases the local name for HTML elements (but not XHTML elements). In later versions, this does not happen, so the property is in lower case for both HTML and XHTML. {{ gecko_minversion_inline("1.9.2") }}
+ Though recent specifications require localName to be defined on the {{domxref("Element")}} interface, Gecko-based browsers still implement it on the {{domxref("Node")}} interface.
+
{{domxref("Node.namespaceURI")}} {{obsolete_inline}}{{readonlyInline}}
+
The namespace URI of this node, or null if it is no namespace. In Firefox 3.5 and earlier, HTML elements are in no namespace. In later versions, HTML elements are in the http://www.w3.org/1999/xhtml namespace in both HTML and XML trees. {{ gecko_minversion_inline("1.9.2") }}
+ Though recent specifications require namespaceURI to be defined on the {{domxref("Element")}} interface, Gecko-based browsers still implement it on the {{domxref("Node")}} interface.
+
{{domxref("Node.nextSibling")}} {{readonlyInline}}
+
Returns a {{domxref("Node")}} representing the next node in the tree, or null if there isn't such node.
+
{{domxref("Node.nodeName")}} {{readonlyInline}}
+
Returns a {{domxref("DOMString")}} containing the name of the Node. The structure of the name will differ with the name type. E.g. An {{domxref("HTMLElement")}} will contain the name of the corresponding tag, like 'audio' for an {{domxref("HTMLAudioElement")}}, a {{domxref("Text")}} node will have the '#text' string, or a {{domxref("Document")}} node will have the '#document' string.
+
{{domxref("Node.nodePrincipal")}} {{Non-standard_inline()}}{{ Fx_minversion_inline("3") }}
+
A {{ Interface("nsIPrincipal") }} representing the node principal.
+
{{domxref("Node.nodeType")}}{{readonlyInline}}
+
Returns an unsigned short representing the type of the node. Possible values are: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
NameValue
ELEMENT_NODE1
ATTRIBUTE_NODE {{deprecated_inline()}}2
TEXT_NODE3
CDATA_SECTION_NODE {{deprecated_inline()}}4
ENTITY_REFERENCE_NODE {{deprecated_inline()}}5
ENTITY_NODE {{deprecated_inline()}}6
PROCESSING_INSTRUCTION_NODE7
COMMENT_NODE8
DOCUMENT_NODE9
DOCUMENT_TYPE_NODE10
DOCUMENT_FRAGMENT_NODE11
NOTATION_NODE {{deprecated_inline()}}12
+
+
{{domxref("Node.nodeValue")}}
+
Is a {{domxref("DOMString")}} representing the value of an object. For most Node types, this returns null and any set operation is ignored. For nodes of type TEXT_NODE ({{domxref("Text")}} objects), COMMENT_NODE ({{domxref("Comment")}} objects), and PROCESSING_INSTRUCTION_NODE ({{domxref("ProcessingInstruction")}} objects), the value corresponds to the text data contained in the object.
+
{{domxref("Node.ownerDocument")}} {{readonlyInline}}
+
Returns the {{domxref("Document")}} that this node belongs to. If no document is associated with it, returns null.
+
{{domxref("Node.parentNode")}} {{readonlyInline}}
+
Returns a {{domxref("Node")}} that is the parent of this node. If there is no such node, like if this node is the top of the tree or if doesn't participate in a tree, this property returns null.
+
{{domxref("Node.parentElement")}} {{readonlyInline}}
+
Returns an {{domxref("Element")}} that is the parent of this node. If the node has no parent, or if that parent is not an {{domxref("Element")}}, this property returns null.
+
{{domxref("Node.prefix")}} {{obsolete_inline}}{{readonlyInline}}
+
Is a {{domxref("DOMString")}} representing the namespace prefix of the node, or null if no prefix is specified.
+ Though recent specifications require prefix to be defined on the {{domxref("Element")}} interface, Gecko-based browsers still implement it on the {{domxref("Node")}} interface.
+
{{domxref("Node.previousSibling")}} {{readonlyInline}}
+
Returns a {{domxref("Node")}} representing the previous node in the tree, or null if there isn't such node.
+
{{domxref("Node.textContent")}}
+
Is a {{domxref("DOMString")}} representing the textual content of an element and all its descendants.
+
+ +

Methods

+ +

Inherits methods from its parents {{domxref("EventTarget")}}.[1]

+ +
+
{{domxref("Node.appendChild()")}}
+
Insert a {{domxref("Node")}} as the last child node of this element.
+
{{domxref("Node.cloneNode()")}}
+
Clone a {{domxref("Node")}}, and optionally, all of its contents. By default, it clones the content of the node.
+
{{domxref("Node.compareDocumentPosition()")}}
+
 
+
{{domxref("Node.contains()")}}
+
 
+
{{domxref("Node.getFeature()")}} {{obsolete_inline}}
+
...
+
{{domxref("Node.getUserData()")}} {{obsolete_inline}}
+
Allows a user to get some {{domxref("DOMUserData")}} from the node.
+
{{domxref("Node.hasAttributes()")}} {{obsolete_inline}}
+
Returns a {{domxref("Boolean")}} indicating if the element has any attributes, or not.
+
{{domxref("Node.hasChildNodes()")}}
+
Returns a {{domxref("Boolean")}} indicating if the element has any child nodes, or not.
+
{{domxref("Node.insertBefore()")}}
+
Inserts the first {{domxref("Node")}} given in a parameter immediately before the second, child of this element, {{domxref("Node")}}.
+
{{domxref("Node.isDefaultNamespace()")}}
+
 
+
{{domxref("Node.isEqualNode()")}}
+
 
+
{{domxref("Node.isSameNode()")}} {{obsolete_inline}}
+
 
+
{{domxref("Node.isSupported()")}} {{obsolete_inline}}
+
Returns a Boolean flag containing the result of a test whether the DOM implementation implements a specific feature and this feature is supported by the specific node.
+
{{domxref("Node.lookupPrefix()")}}
+
 
+
{{domxref("Node.lookupNamespaceURI()")}}
+
 
+
{{domxref("Node.normalize()")}}
+
Clean up all the text nodes under this element (merge adjacent, remove empty).
+
{{domxref("Node.removeChild()")}}
+
Removes a child node from the current element, which must be a child of the current node.
+
{{domxref("Node.replaceChild()")}}
+
Replaces one child {{domxref("Node")}} of the current one with the second one given in parameter.
+
{{domxref("Node.setUserData()")}} {{obsolete_inline}}
+
Allows a user to attach, or remove, {{domxref("DOMUserData")}} to the node.
+
 
+
+ +

Examples

+ +

Browse all child nodes

+ +

The following function recursively cycles all child nodes of a node and executes a callback function upon them (and upon the parent node itself).

+ +
function DOMComb (oParent, oCallback) {
+  if (oParent.hasChildNodes()) {
+    for (var oNode = oParent.firstChild; oNode; oNode = oNode.nextSibling) {
+      DOMComb(oNode, oCallback);
+    }
+  }
+  oCallback.call(oParent);
+}
+ +

Syntax

+ +
DOMComb(parentNode, callbackFunction);
+ +

Description

+ +

Recursively cycle all child nodes of parentNode and parentNode itself and execute the callbackFunction upon them as this objects.

+ +

Parameters

+ +
+
parentNode
+
The parent node (Node Object).
+
callbackFunction
+
The callback function (Function).
+
+ +

Sample usage

+ +

The following example send to the console.log the text content of the body:

+ +
function printContent () {
+  if (this.nodeValue) { console.log(this.nodeValue); }
+}
+
+onload = function () {
+  DOMComb(document.body, printContent);
+};
+ +

Remove all children nested within a node

+ +
Element.prototype.removeAll = function () {
+  while (this.firstChild) { this.removeChild(this.firstChild); }
+  return this;
+};
+ +

Sample usage

+ +
/* ... an alternative to document.body.innerHTML = "" ... */
+document.body.removeAll();
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG', '#interface-node', 'Node')}}{{Spec2('DOM WHATWG')}}Removed the following properties: attributes, namespaceURI, prefix, and localName.
+ Removed the following methods: isSupported(), hasAttributes(), isSameNode(), getFeature(), setUserData(), and getUserData().
{{SpecName('DOM3 Core', 'core.html#ID-1950641247', 'Node')}}{{Spec2('DOM3 Core')}}The methods insertBefore(), replaceChild(), removeChild(), and appendChild() returns one more kind of error (NOT_SUPPORTED_ERR) if called on a {{domxref("Document")}}.
+ The normalize() method has been modified so that {{domxref("Text")}} node can also be normalized if the proper {{domxref("DOMConfiguration")}} flag is set.
+ Added the following methods: compareDocumentPosition(), isSameNode(), lookupPrefix(), isDefaultNamespace(), lookupNamespaceURI(), isEqualNode(), getFeature(), setUserData(), and getUserData().
+ Added the following properties: baseURI and textContent.
{{SpecName('DOM2 Core', 'core.html#ID-1950641247', 'Node')}}{{Spec2('DOM2 Core')}}The ownerDocument property was slightly modified so that {{domxref("DocumentFragment")}} also returns null.
+ Added the following properties: namespaceURI, prefix, and localName.
+ Added the following methods: normalize(), isSupported() and hasAttributes().
{{SpecName('DOM1', 'level-one-core.html#ID-1950641247', 'Node')}}{{Spec2('DOM1')}}Initial definition.
+ +

 

+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.0")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
getFeature(){{obsolete_inline}}{{CompatNo}}Supported from {{CompatGeckoDesktop("1.0")}} to {{CompatGeckoDesktop("6.0")}}.
+ Removed in {{CompatGeckoDesktop("7.0")}}
{{CompatUnknown}}{{CompatNo}}{{CompatNo}}
getUserData(), setUserData() and hasAttributes() {{deprecated_inline}}{{CompatNo}}Supported from {{CompatGeckoDesktop("1.0")}} to {{CompatGeckoDesktop("21.0")}}.
+ Removed in {{CompatGeckoDesktop("22.0")}}
{{CompatUnknown}}{{CompatNo}}{{CompatNo}}
isSameNode() {{obsolete_inline}}{{CompatNo}}Supported from {{CompatGeckoDesktop("1.0")}} to {{CompatGeckoDesktop("9.0")}}.
+ Removed in {{CompatGeckoDesktop("10.0")}}
{{CompatUnknown}}{{CompatNo}}{{CompatNo}}
isSupported() {{obsolete_inline}}{{CompatUnknown}}Supported from {{CompatGeckoDesktop("1.0")}} to {{CompatGeckoDesktop("21.0")}}.
+ Removed in {{CompatGeckoDesktop("22.0")}}
{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
attributes{{CompatNo}}Supported from {{CompatGeckoDesktop("1.0")}} to {{CompatGeckoDesktop("21.0")}}.
+ Moved to {{domxref("Element")}} in {{CompatGeckoDesktop("22.0")}}
{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatGeckoMobile("1.0")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
getFeature(){{obsolete_inline}}{{CompatNo}}Supported from {{CompatGeckoDesktop("1.0")}} to {{CompatGeckoDesktop("6.0")}}.
+ Removed in {{CompatGeckoDesktop("7.0")}}
{{CompatUnknown}}{{CompatNo}}{{CompatNo}}
+
+ +

[1] Webkit and Blink incorrectly do not make Node inherit from {{domxref("EventTarget")}}.

diff --git a/files/vi/web/api/node/insertbefore/index.html b/files/vi/web/api/node/insertbefore/index.html new file mode 100644 index 0000000000..f60a35f3e7 --- /dev/null +++ b/files/vi/web/api/node/insertbefore/index.html @@ -0,0 +1,166 @@ +--- +title: Node.insertBefore() +slug: Web/API/Node/insertBefore +translation_of: Web/API/Node/insertBefore +--- +
{{APIRef("DOM")}}
+ +

Phương thức Node.insertBefore()  chèn một nút trước nút tài liệu tham khảo như một đối tượng con của một đối tượng gốc (đối tượng bố mẹ) cụ thể . Nếu đối tượng con đã cho là một tham chiếu tới tới một đối tượng node đang tồn tại trong tài liệu  , insertBefore() chuyển nó từ vị trí hiện tại  tới vị trí mới (không có yêu cầu nào phải xoá cái nút từ node gốc của nó trước khi thêm nó vào mấy nút khác).

+ +

Vậy có nghĩa là một node thì không thể đồng thời ở tại hai điểm của tài liệu . Vậy, nếu node đã có nguồn gốc của nó rồi thì đối tượng node  sẽ bị chuyển đi trước tiên rồi sau đó bị chèn vào ở vị trí mới . {{domxref("Node.cloneNode()")}} có thể được sử dụng để tạo một bản sao của đối tượng  node trước khi thêm nó vào dưới phần tử gốc mới. Hãy lưu ý rằng những bản sao được tạo nên cùng cloneNode() sẽ không được tự động đồng bộ hoá.

+ +

Nếu tài liệu ttham chiếu node là null thì node cụ thể được thêm vào đuôi của danh sách tập con của đối tượng node gốc.

+ +

Nếu đối tượng  con đã cho là một {{domxref("DocumentFragment")}} thì toàn bộ nội dung của DocumentFragment  sẽ được chuyển đến danh sách tập con của đối tượng gốc cụ thể.

+ +

Cú pháp

+ +
var insertedNode = parentNode.insertBefore(newNode, referenceNode);
+
+ + + +

Nếu referenceNode là null thì newNode isẽ được chèn vào đuôi của danh sách các đối tượng tập con nodes .

+ +
+

referenceNode  không phải  là một tham số  có thể tuỳ chọn -- bạn phải đưa ra một Node hoặc  null. Việc cung cấp nó thất bại hoặc đưa ra những giá trị không hợp lệ có thể sẽ behave  differently( hành xử khác nhau) trong mỗi phiên bản công cụ tìm kiếm khác nhau.

+
+ +

Return value

+ +

Giá trị được trả về sẽ là một phần tử con trừ khi newNode là một {{domxref("DocumentFragment")}}, trong trường hợp {{domxref("DocumentFragment")}} rỗng được trả về.

+ +

Ví dụ

+ +

Example 1

+ +
<div id="parentElement">
+   <span id="childElement">foo bar</span>
+</div>
+
+<script>
+// Create the new node to insert
+var newNode = document.createElement("span");
+
+// Get a reference to the parent node
+var parentDiv = document.getElementById("childElement").parentNode;
+
+// Begin test case [ 1 ] : Exist a childElement --> All working correctly
+var sp2 = document.getElementById("childElement");
+parentDiv.insertBefore(newNode, sp2);
+// End test case [ 1 ]
+
+// Begin test case [ 2 ] : childElement is of Type undefined
+var sp2 = undefined; // Not exist a node of id "childElement"
+parentDiv.insertBefore(newNode, sp2); // Implicit dynamic cast to type Node
+// End test case [ 2 ]
+
+// Begin test case [ 3 ] : childElement is of Type "undefined" ( string )
+var sp2 = "undefined"; // Not exist a node of id "childElement"
+parentDiv.insertBefore(newNode, sp2); // Generate "Type Error: Invalid Argument"
+// End test case [ 3 ]
+</script>
+
+ +

Example 2

+ +
<div id="parentElement">
+  <span id="childElement">foo bar</span>
+</div>
+
+<script>
+// Create a new, plain <span> element
+var sp1 = document.createElement("span");
+
+// Get a reference to the element, before we want to insert the element
+var sp2 = document.getElementById("childElement");
+// Get a reference to the parent element
+var parentDiv = sp2.parentNode;
+
+// Insert the new element into the DOM before sp2
+parentDiv.insertBefore(sp1, sp2);
+</script>
+ +

Không hề có phương thức  insertAfter() nào cả. Nó có thể được mô phỏng bởi phương thức  insertBefore cùng với {{domxref("Node.nextSibling")}}.

+ +

Trong ví dụ trước, sp1 đã chèn được vào sau  sp2 bằng cách dùng :

+ +
parentDiv.insertBefore(sp1, sp2.nextSibling);
+ +

Nếu sp2 không có đối tượng anh em nào tiếp nữa , thì nó hẳn phải là đối tượng con cuối cùng — sp2.nextSibling trả về null, và sp1 sẽ được chèn vào cuối cùng của danh sách tập node con (ngay sau sp2).

+ +

Example 3

+ +

Chèn một phần tử vào phần tử con đứng đầu bằng cách dùng đặc tính firstChild.

+ +
// Get a reference to the element in which we want to insert a new node
+var parentElement = document.getElementById('parentElement');
+// Get a reference to the first child
+var theFirstChild = parentElement.firstChild;
+
+// Create a new element
+var newElement = document.createElement("div");
+
+// Insert the new element before the first child
+parentElement.insertBefore(newElement, theFirstChild);
+ +

Khi phần tử không có con cả (đối tượng con đầu tiên) thì  firstChild là null. Phần tử vẫn được thêm vào bố mẹ đối tượng gốc, sau con út (đối tượng con cuối cùng). Bởi bố mẹ không có con cả nên nó cũng không có con út luôn. Như vậy, phần tử mới sẽ là phần tử duy nhất sau việc chia cắt.

+ +

Khả năng tương thích của công cụ tìm kiếm

+ + + +

{{Compat("api.Node.insertBefore")}}

+ +

Chi tiết

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG','#dom-node-insertbefore','Node.insertBefore')}}{{Spec2('DOM WHATWG')}}Fixes errors in the insertion algorithm
{{SpecName('DOM4','#dom-node-insertbefore','Node.insertBefore')}}{{Spec2('DOM4')}}Describes the algorithm in more detail
{{SpecName('DOM3 Core','core.html#ID-952280727','Node.insertBefore')}}{{Spec2('DOM3 Core')}}No notable changes
{{SpecName('DOM2 Core','core.html#ID-952280727','Node.insertBefore')}}{{Spec2('DOM2 Core')}}No notable changes
{{SpecName('DOM1','level-one-core.html#method-insertBefore','Node.insertBefore')}}{{Spec2('DOM1')}}Introduced
+ +

Xem thêm

+ + diff --git a/files/vi/web/api/node/parentelement/index.html b/files/vi/web/api/node/parentelement/index.html new file mode 100644 index 0000000000..7e1e081325 --- /dev/null +++ b/files/vi/web/api/node/parentelement/index.html @@ -0,0 +1,50 @@ +--- +title: Node.parentElement +slug: Web/API/Node/parentElement +tags: + - API + - Cần tương thích trình duyệt + - Mô hình Đối tượng Văn bản + - Nút + - Thuộc tính +translation_of: Web/API/Node/parentElement +--- +
+
{{APIRef("DOM")}}
+
+ +

Thuộc tính chỉ-đọc Node.parentElement trả về cha của nút DOM {{domxref("Element")}}, hoặcnull nếu nút không có cha hoặc cha của nó không là {{domxref("Element")}} DOM.

+ +

Cú pháp

+ +
parentElement = node.parentElement
+ +

parentElement là thành phần cha của nút hiện tại. Nó luôn luôn là một đối tượng {{domxref("Element")}} DOM, hoặc null.

+ +

Ví dụ

+ +
if (node.parentElement) {
+    node.parentElement.style.color = "red";
+}
+ +

Tương thích trình duyệt

+ +

Trên một vài trình duyệt, thuộc tính parentElement chỉ được xác định trên những nút mà chính nó là một {{domxref("Element")}}. Đặc biệt, nó không xác định trên các nút văn bản.

+ +
+ + +

{{Compat("api.Node.parentElement")}}

+
+ +

Thông số

+ + + +

Xem thêm

+ + diff --git a/files/vi/web/api/node/parentnode/index.html b/files/vi/web/api/node/parentnode/index.html new file mode 100644 index 0000000000..a93e4d8ac9 --- /dev/null +++ b/files/vi/web/api/node/parentnode/index.html @@ -0,0 +1,63 @@ +--- +title: Node.parentNode +slug: Web/API/Node/parentNode +tags: + - API + - Gecko + - Mô hình Đối tượng Tài liệu + - Thuộc tính +translation_of: Web/API/Node/parentNode +--- +
+
{{APIRef("DOM")}}
+
+ +

 

+ +

Thuộc tính chỉ-đọc Node.parentNode trả về cha của một nút xác định trong DOM.

+ +

Cú pháp

+ +
parentNode = node.parentNode
+
+ +

parentNode là cha của nút hiện tại. Cha của một phần tử là một nút Element,một nút Document, hoặc một nút DocumentFragment.

+ +

Ví dụ

+ +
if (node.parentNode) {
+  // loại bỏ một nút khỏi cây, trừ khi
+  // nó không nằm trong cây
+  node.parentNode.removeChild(node);
+}
+ +

Chú ý

+ +

Các nodes Document và DocumentFragment có thể không có cha, vì vậy parentNode có thể luôn trả về giá trị null.

+ +

Nó cũng trả về null nếu nút vừa được tạo và chưa được đính vào cây.

+ +

Tương thích trình duyệt

+ + + +

{{Compat("api.Node.parentNode")}}

+ +

Thông số

+ + + +

Xem thêm

+ + diff --git a/files/vi/web/api/notification/index.html b/files/vi/web/api/notification/index.html new file mode 100644 index 0000000000..829159b490 --- /dev/null +++ b/files/vi/web/api/notification/index.html @@ -0,0 +1,408 @@ +--- +title: Notification +slug: Web/API/notification +translation_of: Web/API/Notification +--- +

{{APIRef("Web Notifications")}}

+ +

The Notification interface of the Notifications API is used to configure and display desktop notifications to the user.

+ +

{{AvailableInWorkers}}

+ +

Hàm khởi tạo

+ +
+
{{domxref("Notification.Notification", "Notification()")}}
+
Creates a new instance of the {{domxref('Notification')}} object.
+
+ +

Properties

+ +

Static properties

+ +

These properties are available only on the Notification object itself.

+ +
+
{{domxref("Notification.permission")}} {{readonlyinline}}
+
A string representing the current permission to display notifications. Possible value are: denied (the user refuses to have notifications displayed), granted (the user accepts having notifications displayed), or default (the user choice is unknown and therefore the browser will act as if the value were denied).
+
+ +

Instance properties

+ +

These properties are available only on instances of the Notification object.

+ +
+
{{domxref("Notification.title")}} {{readonlyinline}}
+
The title of the notification as specified in the options parameter of the constructor.
+
{{domxref("Notification.dir")}} {{readonlyinline}}
+
The text direction of the notification as specified in the options parameter of the constructor.
+
{{domxref("Notification.lang")}} {{readonlyinline}}
+
The language code of the notification as specified in the options parameter of the constructor.
+
{{domxref("Notification.body")}} {{readonlyinline}}
+
The body string of the notification as specified in the options parameter of the constructor.
+
{{domxref("Notification.tag")}} {{readonlyinline}}
+
The ID of the notification (if any) as specified in the options parameter of the constructor.
+
{{domxref("Notification.icon")}} {{readonlyinline}}
+
The URL of the image used as an icon of the notification as specified in the options parameter of the constructor.
+
{{domxref("Notification.data")}} {{readonlyinline}}
+
Returns a structured clone of the notification’s data.
+
{{domxref("Notification.requireInteraction")}} {{readonlyinline}}
+
A {{jsxref("Boolean")}} indicating that on devices with sufficiently large screens, a notification should remain active until the user clicks or dismisses it.
+
{{domxref("Notification.silent")}} {{readonlyinline}}
+
Specifies whether the notification should be silent, i.e. no sounds or vibrations should be issued, regardless of the device settings.
+
{{domxref("Notification.timestamp")}} {{readonlyinline}}
+
Specifies the time at which a notification is created or applicable (past, present, or future).
+
+ +

Unsupported properties

+ +

The following properties are listed in the most up-to-date spec, but are not supported in any browsers yet. It is advisable to keep checking back regularly to see if the status of these has updated, and let us know if you find any out of date information.

+ +
+
{{domxref("Notification.noscreen")}} {{readonlyinline}}
+
Specifies whether the notification firing should enable the device's screen or not.
+
{{domxref("Notification.renotify")}} {{readonlyinline}}
+
Specifies whether the user should be notified after a new notification replaces an old one.
+
{{domxref("Notification.sound")}} {{readonlyinline}}
+
Specifies a sound resource to play when the notification fires, in place of the default system notification sound.
+
{{domxref("Notification.sticky")}} {{readonlyinline}}
+
Specifies whether the notification should be 'sticky', i.e. not easily clearable by the user.
+
{{domxref("Notification.vibrate")}} {{readonlyinline}}
+
Specifies a vibration pattern for devices with vibration hardware to emit.
+
+ +

Event handlers

+ +
+
{{domxref("Notification.onclick")}}
+
A handler for the {{event("click")}} event. It is triggered each time the user clicks on the notification.
+
{{domxref("Notification.onerror")}}
+
A handler for the {{event("error")}} event. It is triggered each time the notification encounters an error.
+
+ +

Obsolete handlers

+ +

The following event handlers are still supported as listed in the {{anch("browser compatibility")}} section below, but are no longer listed in the current spec. I is safe therefore to assume they are obsolete, and may stop working in future browser versions.

+ +
+
{{domxref("Notification.onclose")}}
+
A handler for the {{event("close")}} event. It is triggered when the user closes the notification.
+
{{domxref("Notification.onshow")}}
+
A handler for the {{event("show")}} event. It is triggered when the notification is displayed.
+
+ +

Methods

+ +

Static methods

+ +

These methods are available only on the Notification object itself.

+ +
+
{{domxref("Notification.requestPermission()")}}
+
Requests permission from the user to display notifications.
+
+ +

Instance methods

+ +

These properties are available only on an instance of the Notification object or through its prototype. The Notification object also inherits from the {{domxref("EventTarget")}} interface.

+ +
+
{{domxref("Notification.close()")}}
+
Programmatically closes a notification.
+
+ +

Example

+ +

Assume this basic HTML:

+ +
<button onclick="notifyMe()">Notify me!</button>
+ +

It's possible to send a notification as follows — here we present a fairly verbose and complete set of code you could use if you wanted to first check whether notifications are supported, then check if permission has been granted for the current origin to send notifications, then request permission if required, before then sending a notification.

+ +
function notifyMe() {
+  // Let's check if the browser supports notifications
+  if (!("Notification" in window)) {
+    alert("This browser does not support desktop notification");
+  }
+
+  // Let's check whether notification permissions have already been granted
+  else if (Notification.permission === "granted") {
+    // If it's okay let's create a notification
+    var notification = new Notification("Hi there!");
+  }
+
+  // Otherwise, we need to ask the user for permission
+  else if (Notification.permission !== 'denied') {
+    Notification.requestPermission(function (permission) {
+      // If the user accepts, let's create a notification
+      if (permission === "granted") {
+        var notification = new Notification("Hi there!");
+      }
+    });
+  }
+
+  // At last, if the user has denied notifications, and you
+  // want to be respectful there is no need to bother them any more.
+}
+ +

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

+ +

In many cases, you don't need to be this verbose. For example, in our Emogotchi demo (see source code), we simply run {{domxref("Notification.requestPermission")}} regardless to make sure we can get permission to send notifications (this uses the newer promise-based method syntax):

+ +
Notification.requestPermission().then(function(result) {
+  console.log(result);
+});
+ +

Then we run a simple spawnNotification() function when we want to fire a notification — this is passed arguments to specify the body, icon and title we want, then it creates the necessary options object and fires the notification using the {{domxref("Notification.Notification","Notification()")}} constructor.

+ +
function spawnNotification(theBody,theIcon,theTitle) {
+  var options = {
+      body: theBody,
+      icon: theIcon
+  }
+  var n = new Notification(theTitle,options);
+}
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Notifications')}}{{Spec2('Web Notifications')}}Living standard
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support5{{property_prefix("webkit")}}[1]
+ 22
4.0 {{property_prefix("moz")}}[2]
+ 22
{{CompatNo}}256[3]
icon5{{property_prefix("webkit")}}[1]
+ 22
4.0 {{property_prefix("moz")}}[2]
+ 22
{{CompatNo}}25{{CompatNo}}
Available in workers{{CompatVersionUnknown}}{{CompatGeckoDesktop("41.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
silent{{CompatChrome(43.0)}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
noscreen, sticky{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
sound{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
renotify{{CompatChrome(50.0)}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
Promise-based Notification.requestPermission(){{CompatUnknown}}{{CompatGeckoDesktop("47.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatUnknown}} +

{{CompatVersionUnknown}}

+
4.0{{property_prefix("moz")}}[2]
+ 22
1.0.1{{property_prefix("moz")}}[2]
+ 1.2
{{CompatNo}}{{CompatUnknown}}{{CompatNo}} +

{{CompatVersionUnknown}}

+
icon{{CompatUnknown}}{{CompatVersionUnknown}}4.0{{property_prefix("moz")}}[2]
+ 22
1.0.1{{property_prefix("moz")}}[2]
+ 1.2
{{CompatNo}}{{CompatUnknown}}{{CompatNo}}{{CompatVersionUnknown}}
Available in workers{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("41.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}
silent{{CompatNo}}{{CompatChrome(43.0)}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatChrome(43.0)}}
noscreen, sticky{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
sound{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatVersionUnknown}}
renotify{{CompatNo}}{{CompatChrome(50.0)}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
Promise-based Notification.requestPermission(){{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile("47.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1] Before Chrome 22, the support for notification followed an old prefixed version of the specification and used the {{domxref("window.navigator.webkitNotifications","navigator.webkitNotifications")}} object to instantiate a new notification.

+ +

Before Chrome 32, {{domxref("Notification.permission")}} was not supported.

+ +

Before Chrome 42, service worker additions were not supported.

+ +

Starting in Chrome 49, notifications do not work in incognito mode.

+ +

[2] Prior to Firefox 22 (Firefox OS <1.2), the instantiation of a new notification must be done with the {{domxref("window.navigator.mozNotification", "navigator.mozNotification")}} object through its createNotification method.

+ +

Prior to Firefox 22 (Firefox OS <1.2), the Notification was displayed when calling the show method and supported only the click and close events.

+ +

Nick Desaulniers wrote a Notification shim to cover both newer and older implementations.

+ +

One particular Firefox OS issue is that you can pass a path to an icon to use in the notification, but if the app is packaged you cannot use a relative path like /my_icon.png. You also can't use window.location.origin + "/my_icon.png" because window.location.origin is null in packaged apps. The manifest origin field fixes this, but it is only available in Firefox OS 1.1+. A potential solution for supporting Firefox OS <1.1 is to pass an absolute URL to an externally hosted version of the icon. This is less than ideal as the notification is displayed immediately without the icon, then the icon is fetched, but it works on all versions of Firefox OS.

+ +

When using notifications  in a Firefox OS app, be sure to add the desktop-notification permission in your manifest file. Notifications can be used at any permission level, hosted or above: "permissions": { "desktop-notification": {} }

+ +

[3] Safari started to support notification with Safari 6, but only on Mac OSX 10.8+ (Mountain Lion).

+ +

See also

+ + diff --git a/files/vi/web/api/touch_events/index.html b/files/vi/web/api/touch_events/index.html new file mode 100644 index 0000000000..f723a4f971 --- /dev/null +++ b/files/vi/web/api/touch_events/index.html @@ -0,0 +1,340 @@ +--- +title: Touch events +slug: Web/API/Touch_events +tags: + - Advanced + - DOM + - Event + - Guide + - Mobile + - NeedsTranslation + - Overview + - TopicStub + - touch +translation_of: Web/API/Touch_events +--- +
{{DefaultAPISidebar("Touch Events")}}
+ +

In order to provide quality support for touch-based user interfaces, touch events offer the ability to interpret finger (or stylus) activity on touch screens or trackpads.

+ +

The touch events interfaces are relatively low-level APIs that can be used to support application specific multi-touch interactions such as a two-finger gesture. A multi-touch interaction starts when a finger (or stylus) first touches the contact surface. Other fingers may subsequently touch the surface and optionally move across the touch surface. The interaction ends when the fingers are removed from the surface. During this interaction, an application receives touch events during the start, move and end phases.

+ +

Touch events are similar to mouse events except they support simultaneous touches and at different locations on the touch surface. The {{domxref("TouchEvent")}} interface encapsulates all of the touch points that are currently active. The {{domxref("Touch")}} interface, which represents a single touch point, includes information such as the position of the touch point relative to the browser viewport.

+ +

Definitions

+ +
+
Surface
+
The touch-sensitive surface. This may be a screen or trackpad.
+
+ +
+
Touch point
+
A point of contact with the surface. This may be a finger (or elbow, ear, nose, whatever, but typically a finger) or stylus.
+
+ +

Interfaces

+ +
+
{{domxref("TouchEvent")}}
+
Represents an event that occurs when the state of touches on the surface changes.
+
{{domxref("Touch")}}
+
Represents a single point of contact between the user and the touch surface.
+
{{domxref("TouchList")}}
+
Represents a group of touches; this is used when the user has, for example, multiple fingers on the surface at the same time.
+
+ +

Example

+ +

This example tracks multiple touch points at a time, allowing the user to draw in a {{HTMLElement("canvas")}} with more than one finger at a time. It will only work on a browser that supports touch events.

+ +
Note: The text below uses the term "finger" when describing the contact with the surface, but it could, of course, also be a stylus or other contact method.
+ +

Create a canvas

+ +
<canvas id="canvas" width="600" height="600" style="border:solid black 1px;">
+  Your browser does not support canvas element.
+</canvas>
+<br>
+<button onclick="startup()">Initialize</button>
+<br>
+Log: <pre id="log" style="border: 1px solid #ccc;"></pre>
+
+ +

Setting up the event handlers

+ +

When the page loads, the startup() function shown below should be called by our {{HTMLElement("body")}} element's onload attribute (but in the example we use a button to trigger it, due to limitations of the MDN live example system).

+ +
function startup() {
+  var el = document.getElementsByTagName("canvas")[0];
+  el.addEventListener("touchstart", handleStart, false);
+  el.addEventListener("touchend", handleEnd, false);
+  el.addEventListener("touchcancel", handleCancel, false);
+  el.addEventListener("touchmove", handleMove, false);
+  console.log("initialized.");
+}
+
+ +

This simply sets up all the event listeners for our {{HTMLElement("canvas")}} element so we can handle the touch events as they occur.

+ +

Tracking new touches

+ +

We'll keep track of the touches in-progress.

+ +
var ongoingTouches = [];
+
+ +

When a {{event("touchstart")}} event occurs, indicating that a new touch on the surface has occurred, the handleStart() function below is called.

+ +
function handleStart(evt) {
+  evt.preventDefault();
+  console.log("touchstart.");
+  var el = document.getElementsByTagName("canvas")[0];
+  var ctx = el.getContext("2d");
+  var touches = evt.changedTouches;
+
+  for (var i = 0; i < touches.length; i++) {
+    console.log("touchstart:" + i + "...");
+    ongoingTouches.push(copyTouch(touches[i]));
+    var color = colorForTouch(touches[i]);
+    ctx.beginPath();
+    ctx.arc(touches[i].pageX, touches[i].pageY, 4, 0, 2 * Math.PI, false);  // a circle at the start
+    ctx.fillStyle = color;
+    ctx.fill();
+    console.log("touchstart:" + i + ".");
+  }
+}
+
+ +

This calls {{domxref("event.preventDefault()")}} to keep the browser from continuing to process the touch event (this also prevents a mouse event from also being delivered). Then we get the context and pull the list of changed touch points out of the event's {{domxref("TouchEvent.changedTouches")}} property.

+ +

After that, we iterate over all the {{domxref("Touch")}} objects in the list, pushing them onto an array of active touch points and drawing the start point for the draw as a small circle; we're using a 4-pixel wide line, so a 4 pixel radius circle will show up neatly.

+ +

Drawing as the touches move

+ +

Each time one or more fingers moves, a {{event("touchmove")}} event is delivered, resulting in our handleMove() function being called. Its responsibility in this example is to update the cached touch information and to draw a line from the previous position to the current position of each touch.

+ +
function handleMove(evt) {
+  evt.preventDefault();
+  var el = document.getElementsByTagName("canvas")[0];
+  var ctx = el.getContext("2d");
+  var touches = evt.changedTouches;
+
+  for (var i = 0; i < touches.length; i++) {
+    var color = colorForTouch(touches[i]);
+    var idx = ongoingTouchIndexById(touches[i].identifier);
+
+    if (idx >= 0) {
+      console.log("continuing touch "+idx);
+      ctx.beginPath();
+      console.log("ctx.moveTo(" + ongoingTouches[idx].pageX + ", " + ongoingTouches[idx].pageY + ");");
+      ctx.moveTo(ongoingTouches[idx].pageX, ongoingTouches[idx].pageY);
+      console.log("ctx.lineTo(" + touches[i].pageX + ", " + touches[i].pageY + ");");
+      ctx.lineTo(touches[i].pageX, touches[i].pageY);
+      ctx.lineWidth = 4;
+      ctx.strokeStyle = color;
+      ctx.stroke();
+
+      ongoingTouches.splice(idx, 1, copyTouch(touches[i]));  // swap in the new touch record
+      console.log(".");
+    } else {
+      console.log("can't figure out which touch to continue");
+    }
+  }
+}
+
+ +

This iterates over the changed touches as well, but it looks in our cached touch information array for the previous information about each touch in order to determine the starting point for each touch's new line segment to be drawn. This is done by looking at each touch's {{domxref("Touch.identifier")}} property. This property is a unique integer for each touch, and remains consistent for each event during the duration of each finger's contact with the surface.

+ +

This lets us get the coordinates of the previous position of each touch and use the appropriate context methods to draw a line segment joining the two positions together.

+ +

After drawing the line, we call Array.splice() to replace the previous information about the touch point with the current information in the ongoingTouches array.

+ +

Handling the end of a touch

+ +

When the user lifts a finger off the surface, a {{event("touchend")}} event is sent. We handle this by calling the handleEnd() function below. Its job is to draw the last line segment for each touch that ended and remove the touch point from the ongoing touch list.

+ +
function handleEnd(evt) {
+  evt.preventDefault();
+  log("touchend");
+  var el = document.getElementsByTagName("canvas")[0];
+  var ctx = el.getContext("2d");
+  var touches = evt.changedTouches;
+
+  for (var i = 0; i < touches.length; i++) {
+    var color = colorForTouch(touches[i]);
+    var idx = ongoingTouchIndexById(touches[i].identifier);
+
+    if (idx >= 0) {
+      ctx.lineWidth = 4;
+      ctx.fillStyle = color;
+      ctx.beginPath();
+      ctx.moveTo(ongoingTouches[idx].pageX, ongoingTouches[idx].pageY);
+      ctx.lineTo(touches[i].pageX, touches[i].pageY);
+      ctx.fillRect(touches[i].pageX - 4, touches[i].pageY - 4, 8, 8);  // and a square at the end
+      ongoingTouches.splice(idx, 1);  // remove it; we're done
+    } else {
+      console.log("can't figure out which touch to end");
+    }
+  }
+}
+
+ +

This is very similar to the previous function; the only real differences are that we draw a small square to mark the end and that when we call Array.splice(), we simply remove the old entry from the ongoing touch list, without adding in the updated information. The result is that we stop tracking that touch point.

+ +

Handling canceled touches

+ +

If the user's finger wanders into browser UI, or the touch otherwise needs to be canceled, the {{event("touchcancel")}} event is sent, and we call the handleCancel() function below.

+ +
function handleCancel(evt) {
+  evt.preventDefault();
+  console.log("touchcancel.");
+  var touches = evt.changedTouches;
+
+  for (var i = 0; i < touches.length; i++) {
+    var idx = ongoingTouchIndexById(touches[i].identifier);
+    ongoingTouches.splice(idx, 1);  // remove it; we're done
+  }
+}
+
+ +

Since the idea is to immediately abort the touch, we simply remove it from the ongoing touch list without drawing a final line segment.

+ +

Convenience functions

+ +

This example uses two convenience functions that should be looked at briefly to help make the rest of the code more clear.

+ +

Selecting a color for each touch

+ +

In order to make each touch's drawing look different, the colorForTouch() function is used to pick a color based on the touch's unique identifier. This identifier is an opaque number, but we can at least rely on it differing between the currently-active touches.

+ +
function colorForTouch(touch) {
+  var r = touch.identifier % 16;
+  var g = Math.floor(touch.identifier / 3) % 16;
+  var b = Math.floor(touch.identifier / 7) % 16;
+  r = r.toString(16); // make it a hex digit
+  g = g.toString(16); // make it a hex digit
+  b = b.toString(16); // make it a hex digit
+  var color = "#" + r + g + b;
+  console.log("color for touch with identifier " + touch.identifier + " = " + color);
+  return color;
+}
+
+ +

The result from this function is a string that can be used when calling {{HTMLElement("canvas")}} functions to set drawing colors. For example, for a {{domxref("Touch.identifier")}} value of 10, the resulting string is "#aaa".

+ +

Copying a touch object

+ +

Some browsers (mobile Safari, for one) re-use touch objects between events, so it's best to copy the bits you care about, rather than referencing the entire object.

+ +
function copyTouch(touch) {
+  return { identifier: touch.identifier, pageX: touch.pageX, pageY: touch.pageY };
+}
+ +

Finding an ongoing touch

+ +

The ongoingTouchIndexById() function below scans through the ongoingTouches array to find the touch matching the given identifier, then returns that touch's index into the array.

+ +
function ongoingTouchIndexById(idToFind) {
+  for (var i = 0; i < ongoingTouches.length; i++) {
+    var id = ongoingTouches[i].identifier;
+
+    if (id == idToFind) {
+      return i;
+    }
+  }
+  return -1;    // not found
+}
+
+ +

Showing what's going on

+ +
function log(msg) {
+  var p = document.getElementById('log');
+  p.innerHTML = msg + "\n" + p.innerHTML;
+}
+ +

If your browser supports it, you can {{LiveSampleLink('Example', 'see it live')}}.

+ +

jsFiddle example

+ +

Additional tips

+ +

This section provides additional tips on how to handle touch events in your web application.

+ +

Handling clicks

+ +

Since calling preventDefault() on a {{event("touchstart")}} or the first {{event("touchmove")}} event of a series prevents the corresponding mouse events from firing, it's common to call preventDefault() on {{event("touchmove")}} rather than {{event("touchstart")}}. That way, mouse events can still fire and things like links will continue to work. Alternatively, some frameworks have taken to refiring touch events as mouse events for this same purpose. (This example is oversimplified and may result in strange behavior. It is only intended as a guide.)

+ +
function onTouch(evt) {
+  evt.preventDefault();
+  if (evt.touches.length > 1 || (evt.type == "touchend" && evt.touches.length > 0))
+    return;
+
+  var newEvt = document.createEvent("MouseEvents");
+  var type = null;
+  var touch = null;
+
+  switch (evt.type) {
+    case "touchstart":
+      type = "mousedown";
+      touch = evt.changedTouches[0];
+      break;
+    case "touchmove":
+      type = "mousemove";
+      touch = evt.changedTouches[0];
+      break;
+    case "touchend":
+      type = "mouseup";
+      touch = evt.changedTouches[0];
+      break;
+  }
+
+  newEvt.initMouseEvent(type, true, true, evt.originalTarget.ownerDocument.defaultView, 0,
+    touch.screenX, touch.screenY, touch.clientX, touch.clientY,
+    evt.ctrlKey, evt.altKey, evt.shiftKey, evt.metaKey, 0, null);
+  evt.originalTarget.dispatchEvent(newEvt);
+}
+
+ +

Calling preventDefault() only on a second touch

+ +

One technique for preventing things like pinchZoom on a page is to call preventDefault() on the second touch in a series. This behavior is not well defined in the touch events spec, and results in different behavior for different browsers (i.e., iOS will prevent zooming but still allow panning with both fingers; Android will allow zooming but not panning; Opera and Firefox currently prevent all panning and zooming.) Currently, it's not recommended to depend on any particular behavior in this case, but rather to depend on meta viewport to prevent zooming.

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Touch Events 2', '#touch-interface', 'Touch')}}{{Spec2('Touch Events 2')}}Added radiusX, radiusY, rotationAngle, force properties
{{SpecName('Touch Events', '#touch-interface', 'Touch')}}{{Spec2('Touch Events')}}Initial definition.
+ +

Browser compatibility

+ +

Touch

+ + + +

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

+ +

Firefox, touch events, and multiprocess (e10s)

+ +

In Firefox, touch events are disabled when e10s (electrolysis; multiprocess Firefox) is disabled. e10s is on by default in Firefox, but can end up becoming disabled in certain situations, for example when certain accessibility tools or Firefox add-ons are installed that require e10s to be disabled to work. This means that even on a touchscreen-enabled desktop/laptop, touch events won't be enabled.

+ +

You can test whether e10s is disabled by going to about:support and looking at the "Multiprocess Windows" entry in the "Application Basics" section. 1/1 means it is enabled, 0/1 means disabled.

+ +

If you want to force e10s to be on — to explicitly re-enable touch events support — you need to go to about:config and create a new Boolean preference browser.tabs.remote.force-enable. Set it to true, restart the browser, and e10s will be enabled regardless of any other settings.

diff --git a/files/vi/web/api/touch_events/supporting_both_touchevent_and_mouseevent/index.html b/files/vi/web/api/touch_events/supporting_both_touchevent_and_mouseevent/index.html new file mode 100644 index 0000000000..33ca3f4490 --- /dev/null +++ b/files/vi/web/api/touch_events/supporting_both_touchevent_and_mouseevent/index.html @@ -0,0 +1,61 @@ +--- +title: Supporting both TouchEvent and MouseEvent +slug: Web/API/Touch_events/Supporting_both_TouchEvent_and_MouseEvent +translation_of: Web/API/Touch_events/Supporting_both_TouchEvent_and_MouseEvent +--- +

{{DefaultAPISidebar("Touch Events")}}

+ +

{{domxref("Touch_events","touch")}} interface cho phép cung cấp các tương tác với ứng dụng trên thiết bị. Tuy nhiên, sự thật là đa số các web hiện tại được thiết kế để làm việc với trỏ chuột. Thậm chí, khi trình duyệt hổ trợ touch, trình duyệt vẫn phải giả lập sự kiện của chuột.

+ +

Event firing

+ +

Touch event đưa ra vài yêu cầu cho trình duyệt (xem Interaction with Mouse Events and click để xem chi tiết), lưu ý răng trình duyệt có thể fire cả 2 sự kiện touch và mouse để đáp lại cùng một tương tác của user

+ +

Nếu trình duyệt fire cả 2 sự kiện touch và mouse cho cùng tương tác, trình duyệt phải  fire {{event("touchstart")}} trước khi fire sự kiện mouse. Vì vậy, nếu ứng dụng không muốn sử dụng sự kiện mouse trên một element {{domxref("Touch.target","target")}}, chúng ta phải gọi {{domxref("Event.preventDefault()","preventDefault()")}}.

+ +

Đây là một snippet code dùng {{event("touchmove")}} event handler và gọi preventDefault().

+ +
// touchmove handler
+function process_touchmove(ev) {
+  // Call preventDefault() to prevent any further handling
+  ev.preventDefault();
+}
+
+ +

Thứ tự Event

+ +

Thứ tự của các sự kiện touch và mouse được định nghĩa như sau:

+ + + +

Nếu {{event("touchstart")}}, {{event("touchmove")}} hoặc {{event("touchend")}} được hủy, sẽ không có sự mouse hoặc click nào được fire, thứ tự sẽ là:

+ + + +

Community

+ + + + + + diff --git a/files/vi/web/api/url_api/index.html b/files/vi/web/api/url_api/index.html new file mode 100644 index 0000000000..71626f5c4a --- /dev/null +++ b/files/vi/web/api/url_api/index.html @@ -0,0 +1,122 @@ +--- +title: URL API +slug: Web/API/URL_API +translation_of: Web/API/URL_API +--- +

{{DefaultAPISidebar("URL API")}}

+ +

The URL API is a component of the URL standard, which defines what constitutes a valid {{Glossary("URL", "Uniform Resource Locator")}} and the API that accesses and manipulates URLs. The URL standard also defines concepts such as domains, hosts, and IP addresses, and also attempts to describe in a standard way the legacy application/x-www-form-urlencoded {{Glossary("MIME type")}} used to submit web forms' contents as a set of key/value pairs.

+ +

Mô hình URL và cách sử dụng

+ +

Phần lớn tiêu chuẩn URL được lấy theo định nghĩa của URL cùng cấu trúc và phân tích cú pháp. Nó cũng bao gồm các định nghĩa về các thuật ngữ khác nhau liên quan đến việc đánh địa chỉ các máy tính trên mạng, các thuật toán để phân tích địa chỉ IP và địa chỉ DOM được chỉ định.

+ +

Truy cập component URL

+ +

Tạo object {{domxref("URL")}} đối với một URL đã cho sẽ phân tích cú pháp URL và cung cấp quyền truy cập nhanh vào các thành phần của nó.

+ +
let addr = new URL("https://wiki.developer.mozilla.org/vi/docs/Web/API/URL_API");
+let host = addr.host;
+let path = addr.pathname;
+
+ +

Mã trên tạo ra 1 object URL cho bài viết bạn đang đọc, rồi lấy thuộc tính {{domxref("URL.host", "host")}} và {{domxref("URL.pathname", "pathname")}}. Trong tình huống trên, các giá trị tương ứng lần lượt là wiki.developer.mozilla.org/vi/docs/Web/API/URL_API.

+ +

Thay đổi URL

+ +

Hầu hết các thuộc tính của URL là cố định; bạn có thể viết các giá trị mới cho chúng để thay đổi URL. Ví dụ: để tạo URL mới và đặt tên người dùng:

+ +
let myUsername = "someguy";
+let addr = new URL("https://mysite.com/login");
+addr.username = myUsername;
+
+ +

Đặt giá trị của {{domxref("URL.username", "username")}} không chỉ thay đổi giá trị của thuộc tính, mà còn thay đổi cả đường dẫn URL. Sau khi thực thi đoạn code, giá trị trả về của {{domxref("URL.href", "addr.href")}} là https://someguy@mysite.com/login. Điều này đúng với mọi thuộc tính có thể ghi.

+ +

Truy vấn

+ +

Thuộc tính {{domxref("URL.search", "search")}} trong URL chứa các giá trị truy vấn của URL. Lấy ví dụ, nếu đường dẫn URL là https://mysite.com/login?user=someguy&page=news, thì giá trị của thuộc tính search?user=someguy&page=news. Bạn có thể kiểm tra các giá trị của mỗi tham số với {{domxref("URLSearchParams")}} là object của phương thức {{domxref("URLSearchParams.get", "get()")}}:

+ +
let addr = new URL("https://mysite.com/login?user=someguy&page=news");
+try {
+  loginUser(addr.searchParams.get("user"));
+  gotoPage(addr.searchParams.get("page"));
+} catch(err) {
+  showErrorMessage(err);
+}
+
+ +

Với ví dụ trên, username và trang đích được lấy từ query và chuyển vào trong function được dùng để điều hướng người dùng đăng nhập và chuyển tới trang đích mong muốn.

+ +

Other functions within URLSearchParams let you change the value of keys, add and delete keys and their values, and even sort the list of parameters.

+ +

URL API interfaces

+ +

The URL API is a simple one, with only a couple of interfaces to its name:

+ +
+ +
+ +

Older versions of the specification included an interface called {{domxref("URLUtilsReadOnly")}}, which has since been merged into the {{domxref("WorkerLocation")}} interface.

+ +

Ví dụ

+ +

If you want to process the parameters included in a URL, you could do it manually, but it's much easier to create a URL object to do it for you. The fillTableWithParameters() function below takes as input a {{domxref("HTMLTableElement")}} object representing a {{HTMLElement("table")}}. Rows are added to the table, one for each key found in the parameters, with the first column containing the key's name, and the second column having the value.

+ +

Note the call to {{domxref("URLSearchParams.sort()")}} to sort the parameter list before generating the table.

+ +
function fillTableWithParameters(tbl) {
+  let url = new URL(document.location.href);
+  url.searchParams.sort();
+  let keys = url.searchParams.keys();
+
+  for (let key of keys) {
+    let val = url.searchParams.get(key);
+    let row = document.createElement("tr");
+    let cell = document.createElement("td");
+    cell.innerText = key;
+    row.appendChild(cell);
+    cell = document.createElement("td");
+    cell.innerText = val;
+    row.appendChild(cell);
+    tbl.appendChild(row);
+  };
+}
+ +

A working version of this example can be found on Glitch. Just add parameters to the URL when loading the page to see them in the table. For instance, try https://url-api.glitch.me?from=mdn&excitement=high&likelihood=inconceivable.

+ +

Quy chuẩn

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('URL')}}{{Spec2('URL')}}WHATWG specification
+ +

Tương thích trình duyệt

+ +
+ + +

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

+
+ +

Xem thêm

+ + diff --git a/files/vi/web/api/webrtc_api/index.html b/files/vi/web/api/webrtc_api/index.html new file mode 100644 index 0000000000..508df4945f --- /dev/null +++ b/files/vi/web/api/webrtc_api/index.html @@ -0,0 +1,233 @@ +--- +title: WebRTC API +slug: Web/API/WebRTC_API +tags: + - API + - Audio + - Conferencing + - Landing + - Media + - NeedsTranslation + - Networking + - TopicStub + - Video + - WebRTC + - WebRTC API + - streaming +translation_of: Web/API/WebRTC_API +--- +
{{WebRTCSidebar}}
+ +

WebRTC (Web Real-Time Communication) is a technology which enables Web applications and sites to capture and optionally stream audio and/or video media, as well as to exchange arbitrary data between browsers without requiring an intermediary. The set of standards that comprise WebRTC makes it possible to share data and perform teleconferencing peer-to-peer, without requiring that the user installs plug-ins or any other third-party software.

+ +

WebRTC consists of several interrelated APIs and protocols which work together to achieve this. The documentation you'll find here will help you understand the fundamentals of WebRTC, how to set up and use both data and media connections, and more.

+ +

Interoperability

+ +

Because implementations of WebRTC are still evolving, and because each browser has different levels of support for codecs and WebRTC features, you should strongly consider making use of the Adapter.js library provided by Google before you begin to write your code.

+ +

Adapter.js uses shims and polyfills to smooth over the differences among the WebRTC implementations across the environments supporting it. Adapter.js also handles prefixes and other naming differences to make the entire WebRTC development process easier, with more broadly compatible results. The library is also available as an NPM package.

+ +

To learn more about Adapter.js, see Improving compatibility using WebRTC adapter.js.

+ +

WebRTC concepts and usage

+ +

WebRTC serves multiple purposes; together with the Media Capture and Streams API, they provide powerful multimedia capabilities to the Web, including support for audio and video conferencing, file exchange, screen sharing, identity management, and interfacing with legacy telephone systems including support for sending {{Glossary("DTMF")}} (touch-tone dialing) signals. Connections between peers can be made without requiring any special drivers or plug-ins, and can often be made without any intermediary servers.

+ +

Connections between two peers are represented by the {{DOMxRef("RTCPeerConnection")}} interface. Once a connection has been established and opened using RTCPeerConnection, media streams ({{DOMxRef("MediaStream")}}s) and/or data channels ({{DOMxRef("RTCDataChannel")}}s) can be added to the connection.

+ +

Media streams can consist of any number of tracks of media information; tracks, which are represented by objects based on the {{DOMxRef("MediaStreamTrack")}} interface, may contain one of a number of types of media data, including audio, video, and text (such as subtitles or even chapter names). Most streams consist of at least one audio track and likely also a video track, and can be used to send and receive both live media or stored media information (such as a streamed movie).

+ +

You can also use the connection between two peers to exchange arbitrary binary data using the {{DOMxRef("RTCDataChannel")}} interface. This can be used for back-channel information, metadata exchange, game status packets, file transfers, or even as a primary channel for data transfer.

+ +

more details and links to relevant guides and tutorials needed

+ +

WebRTC interfaces

+ +

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

+ +

Connection setup and management

+ +

These interfaces are used to set up, open, and manage WebRTC connections. Included are interfaces representing peer media connections, data channels, and interfaces used when exchanging information on the capabilities of each peer in order to select the best possible configuration for a two-way media connection..

+ +
+
{{DOMxRef("RTCPeerConnection")}}
+
Represents a WebRTC connection between the local computer and a remote peer. It is used to handle efficient streaming of data between the two peers.
+
{{DOMxRef("RTCDataChannel")}}
+
Represents a bi-directional data channel between two peers of a connection.
+
{{DOMxRef("RTCDataChannelEvent")}}
+
Represents events that occur while attaching a {{DOMxRef("RTCDataChannel")}} to a {{DOMxRef("RTCPeerConnection")}}. The only event sent with this interface is {{event("datachannel")}}.
+
{{DOMxRef("RTCSessionDescription")}}
+
Represents the parameters of a session. Each RTCSessionDescription consists of a description {{DOMxRef("RTCSessionDescription.type", "type")}} indicating which part of the offer/answer negotiation process it describes and of the {{Glossary("SDP")}} descriptor of the session.
+
{{DOMxRef("RTCSessionDescriptionCallback")}}
+
The RTCSessionDescriptionCallback is passed into the {{DOMxRef("RTCPeerConnection")}} object when requesting it to create offers or answers.
+
{{DOMxRef("RTCStatsReport")}}
+
Provides information detailing statistics for a connection or for an individual track on the connection; the report can be obtained by calling {{DOMxRef("RTCPeerConnection.getStats()")}}. Details about using WebRTC statistics can be found in WebRTC Statistics API.
+
{{DOMxRef("RTCIceCandidate")}}
+
Represents a candidate Internet Connectivity Establishment ({{Glossary("ICE")}}) server for establishing an {{DOMxRef("RTCPeerConnection")}}.
+
{{DOMxRef("RTCIceTransport")}}
+
Represents information about an ICE transport.
+
{{DOMxRef("RTCIceServer")}}
+
Defines how to connect to a single ICE server (such as a {{Glossary("STUN")}} or {{Glossary("TURN")}} server).
+
{{DOMxRef("RTCPeerConnectionIceEvent")}}
+
Represents events that occur in relation to ICE candidates with the target, usually an {{DOMxRef("RTCPeerConnection")}}. Only one event is of this type: {{event("icecandidate")}}.
+
{{DOMxRef("RTCRtpSender")}}
+
Manages the encoding and transmission of data for a {{DOMxRef("MediaStreamTrack")}} on an {{DOMxRef("RTCPeerConnection")}}.
+
{{DOMxRef("RTCRtpReceiver")}}
+
Manages the reception and decoding of data for a {{DOMxRef("MediaStreamTrack")}} on an {{DOMxRef("RTCPeerConnection")}}.
+
{{DOMxRef("RTCRtpContributingSource")}}
+
Contains information about a given contributing source (CSRC) including the most recent time a packet that the source contributed was played out.
+
{{DOMxRef("RTCTrackEvent")}}
+
The interface used to represent a {{domxref("RTCPeerConnection.track_event", "track")}} event, which indicates that an {{DOMxRef("RTCRtpReceiver")}} object was added to the {{DOMxRef("RTCPeerConnection")}} object, indicating that a new incoming {{DOMxRef("MediaStreamTrack")}} was created and added to the RTCPeerConnection.
+
{{DOMxRef("RTCConfiguration")}}
+
Used to provide configuration options for an RTCPeerConnection.
+
+ +
+
{{DOMxRef("RTCSctpTransport")}}
+
Provides information which describes a Stream Control Transmission Protocol ({{Glossary("SCTP")}}) transport and also provides a way to access the underlying Datagram Transport Layer Security ({{Glossary("DTLS")}}) transport over which SCTP packets for all of an RTCPeerConnection's data channels are sent and received.
+
{{DOMxRef("RTCSctpTransportState")}}
+
Indicates the state of an {{DOMxRef("RTCSctpTransport")}} instance.
+
+ +

Identity and security

+ +

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

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

Telephony

+ +

These interfaces are related to interactivity with Public-Switched Telephone Networks (PTSNs).

+ +
+
{{DOMxRef("RTCDTMFSender")}}
+
Manages the encoding and transmission of Dual-Tone Multi-Frequency ({{Glossary("DTMF")}}) signaling for an {{DOMxRef("RTCPeerConnection")}}.
+
{{DOMxRef("RTCDTMFToneChangeEvent")}}
+
Used by the {{domxref("RTCDTMFSender.tonechange_event", "tonechange")}} event to indicate that a DTMF tone has either begun or ended. This event does not bubble (except where otherwise stated) and is not cancelable (except where otherwise stated).
+
+ +

Guides

+ +
+
Introduction to WebRTC protocols
+
This article introduces the protocols on top of which the WebRTC API is built.
+
WebRTC connectivity
+
A guide to how WebRTC connections work and how the various protocols and interfaces can be used together to build powerful communication apps.
+
Lifetime of a WebRTC session
+
WebRTC lets you build peer-to-peer communication of arbitrary data, audio, or video—or any combination thereof—into a browser application. In this article, we'll look at the lifetime of a WebRTC session, from establishing the connection all the way through closing the connection when it's no longer needed.
+
Establishing a connection: The perfect negotiation pattern
+
Perfect negotiation is a design pattern which is recommended for your signaling process to follow, which provides transparency in negotiation while allowing both sides to be either the offerer or the answerer, without significant coding needed to differentiate the two.
+
Signaling and two-way video calling
+
A tutorial and example which turns 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.
+
Codecs used by WebRTC
+
A guide to the codecs which WebRTC requires browsers to support as well as the optional ones supported by various popular browsers. Included is a guide to help you choose the best codecs for your needs.
+
Using WebRTC data channels
+
This guide covers how you can use a peer connection and an associated {{DOMxRef("RTCDataChannel")}} to exchange arbitrary data between two peers.
+
Using DTMF with WebRTC
+
WebRTC's support for interacting with gateways that link to old-school telephone systems includes support for sending DTMF tones using the {{DOMxRef("RTCDTMFSender")}} interface. This guide shows how to do so.
+
+ +

Tutorials

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

Resources

+ +

Protocols

+ +

WebRTC-proper protocols

+ + + + + + + +

WebRTC statistics

+ + + +

Specifications

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

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

+ + + + diff --git a/files/vi/web/api/webrtc_api/protocols/index.html b/files/vi/web/api/webrtc_api/protocols/index.html new file mode 100644 index 0000000000..8d3bcb81e4 --- /dev/null +++ b/files/vi/web/api/webrtc_api/protocols/index.html @@ -0,0 +1,57 @@ +--- +title: Introduction to WebRTC protocols +slug: Web/API/WebRTC_API/Protocols +translation_of: Web/API/WebRTC_API/Protocols +--- +
{{WebRTCSidebar}}{{draft}}
+ +

Bài viết này giới thiệu các giao thức của WebRTC API được đã được xây dựng.

+ +

ICE

+ +

Interactive Connectivity Establishment (ICE) là một khuân mẫu cho phép trình duyệt của bạn kết nối với các trình duyệt khác. Có rất nhiều lý do tại sao việc kết nối trực tiếp từ A đến B một cách đơn giản sẽ không làm việc. Nó cần vượt qua firewall cái đã ngăn chặn mở môt cuộc kết nối trực tiếp, nó cung cấp cho bạn một địa chỉ duy nhất, trong hầu hết các trường hợp thiết bị của bạn không có địa chỉ public I, và chuyển tiếp dữ liệu thông qua một server nếu bộ định tuyến (router) của bạn không cho phép bạn kết nối một cách trực tiếp với browser khác. ICE sử dụng STUN hoặc TURN hay cả hai server để hoàn thành việc này như đã mô tả ở trên.

+ +

STUN

+ +

Session Traversal Utilities for NAT (STUN) (Từ viết tắt trong một từ viết tắt) là một giao thức để phát hiện ra địa chỉ IP pubic của bạn và xác định bất cứ hạn chế nào trong bộ định tuyến (router) của bạn đã ngăn chặn một cuộc kết nối trực tiếp với các browsers.

+ +

Client sẽ gửi một yêu cầu tới STUN server thông qua internet, STUN server sẽ phản hồi địa chỉ IP public và client có thể có hoặc không truy cập được phìa sau bộ định tuyến NAT.

+ +

An interaction between two users of a WebRTC application involving a STUN server.

+ +

NAT

+ +

Network Address Translation (NAT) được sử dụng để cung cấp cho thiết bị của bạn một địa chỉ IP public. Một bộ định tuyến (router) sẽ có một đia chỉ IP public và mỗi thiết bị được kết nối đến router sẽ có một đia chỉ IP private. Các requests sẽ được chuyển đổi từ địa chỉ IP private sang địa chỉ IP pubic với một cổng (port) duy nhất. Với cách này bạn không cần một địa chỉ IP public riêng cho từng thiết bị nhưng vẫn có thể được phát hiện trên internet.

+ +

Một vài bộ định tuyến (routers) sẽ có những ngăn cản kết nối tới những thiết bị trên network. Điều này có nghĩa là ngay cả việc chúng ta có địa chỉ IP public đã được tìm ra bở STUN server, nhưng không một ai có thể tạo ra một kết nối. Trong tình huốn này chúng ta cần chuyển sang TURN.

+ +

TURN

+ +

Một vài bộ định tuyến (routers) sử dụng NAT được gọi là 'Symmetric NAT'. Nghĩa là bộ định tuyến (router) chỉ chấp nhận kết nối từ những peer mà bạn đã kết nối trước đó.

+ +

Traversal Using Relays around NAT (TURN) có nghĩa là vượt qua hạn chế Symmetric NAT bằng các mở một kết nối với TURN server và truyền tải tất cả thông tin thông qua TURN server. Bạn sẽ tạo một kết nối với một TURN server và nói với tất cả các peer để gửi những gói tin đến server để sau đó nó sẽ chuyển lại cho bạn. Điều này rõ ràng đi kèm với các loại chi phí vì vậy nó chỉ được sử dụng nếu không có lựa chon nào thay thế.

+ +

An interaction between two users of a WebRTC application involving STUN and TURN servers.

+ +

SDP

+ +

Session Description Protocol (SDP) là một tiêu chuẩn mô tả cho những nội dung đa phương tiện của một kết nối như độ phân giản (resolution), định dạn (formats), mã (codecs), mã hóa (encryption), v.v. cho nên tất cả các peers có thể hiểu những loại dữ liệu đang gửi đi. Vì vậy đây là siêu dữ liệu mô tả nội dung chứ không phải chính nội dung đa phương tiện.

+ +

Về mặt kỹ thuận, SDP không thực sự là một protocol, nhưng định dạng data được sử dụng để mô tả kết nối chia sẻ đa phương tiện giữa các thiết bị.

+ +

Documenting SDP is well outside the scope of this documentation; however, there are a few things worth noting here.

+ +

Tài liệu SDP nằm ngoài phạm vi của tài liệu này. Tuy nhiên, có một vài thứ thực sự đáng chú ý ở đây.

+ +

Cấu trúc

+ +

SDP bao gồm một hay nhiều dòng text UTF-8, mỗi dòng bắt đầu với một kiểu ký tự, theo sau là một ký tự dấu bằng ("="), theo sau nữa là nội dung có cấu trúc bao gồm giá trị hay mô tả mà định dạng của nó phụ thuộc vào kiểu. Những dòng nội dung bắt đầu với một chữ (letter) thường được gọi là "letter-lines". Ví dụ, những dòng cung cấp mô tả đa phương tiện có kiểu "m", vì vậy những dòng của nó được xem như là "m-lines"

+ +

Thông tin tham khảo

+ +

Để tìm hiểu thêm về SDP, tham khảo những tài liệu hữu ích dưới đây:

+ + diff --git a/files/vi/web/api/websockets_api/index.html b/files/vi/web/api/websockets_api/index.html new file mode 100644 index 0000000000..e69c174077 --- /dev/null +++ b/files/vi/web/api/websockets_api/index.html @@ -0,0 +1,253 @@ +--- +title: The WebSocket API (WebSockets) +slug: Web/API/WebSockets_API +tags: + - API + - Client + - Communication + - NeedsTranslation + - Overview + - Server + - TopicStub + - Two-Way + - WebSocket + - WebSocket API + - WebSockets + - data + - interactive +translation_of: Web/API/WebSockets_API +--- +

{{DefaultAPISidebar("Websockets API")}}

+ +

Các WebSocket API là một công nghệ tiên tiến mà nó có thể tạo ra một phiên giao tiếp tương tác hai chiều giữa trình duyệt của người dùng và một máy chủ (server). Với API này, bạn có thể gửi những thông báo tới một máy chủ và nhận những phản hồi (response) hướng sự kiện (event-driven) mà không phải liên tục gửi yêu cầu máy chủ để nhận một câu trả lời.

+ +
+

Chú ý: Mặc dù một kết nối Websocket có một số tính năng hơi giống với các socket kiểu Unix chuẩn, Nhưng chúng lại không có liên quan gì với nhau.

+
+ +

Giao diện (Interfaces)

+ +
+
WebSocket
+
Một giao diện cơ bản cho việc kết nối tới một máy chủ Websocket và sau đó là việc gửi và nhận dữ liệu trên kết nối đó.
+
CloseEvent
+
Sự kiện được gửi đi từ một đối tượng Websocket khi kết nối được đóng lại.
+
MessageEvent
+
Sự kiện được gửi bởi đối tượng Websocket khi một thông điệp được nhận từ một máy chủ.
+
+ +

Công cụ

+ + + + + + + +

 

+ +

Đặc tả

+ + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComments
{{SpecName("HTML WHATWG", "web-sockets.html", "WebSocket API")}}{{Spec2("HTML WHATWG")}} 
WebSocketsCandidate Recommendation 
{{RFC(6455, "The WebSocket Protocol")}}IETF RFC 
+ +

 

+ +

Xem thêm

+ + + +

Khả năng tương thích với các trình duyệt

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Tính năngChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Version -76 support {{obsolete_inline}}6{{CompatNo}}{{CompatGeckoDesktop("2.0")}}{{CompatNo}}11.00 (disabled)5.0.1
Protocol version 7 support {{obsolete_inline}}{{CompatNo}}{{CompatNo}}{{CompatGeckoDesktop("6.0")}}
+ {{property_prefix("Moz")}}
{{CompatNo}}{{CompatNo}}{{CompatNo}}
Protocol version 10 support {{obsolete_inline}}14{{CompatNo}}{{CompatGeckoDesktop("7.0")}}
+ {{property_prefix("Moz")}}
HTML5 Labs{{CompatUnknown}}{{CompatUnknown}}
Standard - RFC 6455 Support4314{{CompatGeckoDesktop("48.0")}}1012.106.0
Usable in Workers{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoDesktop("37.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Version -76 support {{obsolete_inline}}{{CompatUnknown}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Protocol version 7 support {{obsolete_inline}}{{CompatUnknown}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Protocol version 8 support (IETF draft 10) {{obsolete_inline}}{{CompatUnknown}}{{CompatNo}}{{CompatGeckoMobile("7.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Standard - RFC 6455 Support4.4(Yes){{CompatGeckoDesktop("11.0")}}{{CompatUnknown}}12.106.0
Usable in Workers{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("37.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

Chú ý về Gecko

+ +

Việc hỗ trợ Websocket trên Firefox đang được tiếp tục với việc theo dõi sư thay đổi của đặc tả Websocket. Firefox 6 triển khai phiên bản 7 của các giao thức cơ bản, trong khi Firefox 7 triển khai phiên bản 8 (như mô tả bởi IETF draft 10). Firefox di đông đón nhận sự hỗ trợ WebSocket từ phiên bản Firefox di động 7.0.

+ +

Gecko 6.0

+ +

Trước Gecko 6.0 {{geckoRelease("6.0")}}, Đã có, không chính xác, một đối tượng WebSocket mà một số trang đã nghĩ rằng đó là việc bao hàm các dịch vụ WebSocket không có tiền tố; Đối tượng này vừa được đổi tên thành MozWebSocket.

+ +

Gecko 7.0

+ +

Bắt đầu từ phiên bản Gecko 7.0 {{geckoRelease("7.0")}}, thông số network.websocket.max-connections được sử dụng để xác định số lượng kết nối websocket tối đa có thể được mở trong một khoảng thời gian nhất định. Giá trị mặc định là 200.

+ +

Gecko 8.0

+ +

Bắt đầu từ phiên bản Gecko 8.0 {{geckoRelease("8.0")}}, phần mở rộng của luồng deflate-stream tới giao thức WebSocket đã bị vô hiệu hóa, bởi vì nó không còn được dùng trong các bản đặc tả. Điều này giải quyết vấn đề không tương thích giữa một số trang web.

+ +

Gecko 11.0

+ +

Trước phiên bản Gecko 11.0, Cả thông điệp đến và đi đều bị giới hạn ở kích thức 16MB. Bây giờ chúng có thể lên đến kích thước 2GB. Chú ý, tuy vậy vẫn còn tùy thuộc vào kích thước bộ nhớ (đặc biệt là trên thiết bị di động) làm cho nó chỉ là kích thước lý thuyết không phải là kích thước thực tế. Trong thực tế, việc truyền các dữ liệu kích thước như vậy sẽ thất bại nếu thiết bị không có đủ bộ nhớ.

+ +

Ngoài ra, ArrayBuffer hỗ trợ cho việc gửi và nhận dữ liệu nhị phân đã được triển khai.

+ +

Kể từ phiên bản Gecko 11.0, API Websocket không còn được thêm tiền tố nữa.

diff --git a/files/vi/web/api/websockets_api/writing_a_websocket_server_in_java/index.html b/files/vi/web/api/websockets_api/writing_a_websocket_server_in_java/index.html new file mode 100644 index 0000000000..6258f6236f --- /dev/null +++ b/files/vi/web/api/websockets_api/writing_a_websocket_server_in_java/index.html @@ -0,0 +1,217 @@ +--- +title: Writing a WebSocket server in Java +slug: Web/API/WebSockets_API/Writing_a_WebSocket_server_in_Java +tags: + - WebSocket +translation_of: Web/API/WebSockets_API/Writing_a_WebSocket_server_in_Java +--- +

Giới thiệu

+ +

Đây là một ví dụ để cho bạn biết thế nào là  một WebSocket API server sử dụng Oracle Java.
+
+ Mặc dù có nhiều ngôn ngữ sercer-side khác nhau bạn có thể sử dụng để tạo một WebSocket server, đây là ví dụ sử dụng Oracle Java code đơn giản.

+ +

Sever này phù hợp tiêu chuẩn RFC 6455, vì vậy nó chỉ kết nối từ  Chrome version 16, Firefox 11, IE 10 và cao hơn.

+ +

Bước 1:

+ +

WebSockets truyền đạt về một TCP (Transmission Control Protocol)  kết nối. Lớp Java's ServerSocket là nằm ở trong gói  java.net.

+ +

ServerSocket

+ +

Xây dựng:

+ +
ServerSocket(int port)
+ +

Khi bạn thuyết trình về ServerSocket class, it is bound to the port number you specified by the port argument.

+ +

Here's how to implement what we have learnt:

+ +
import java.net.ServerSocket;
+import java.net.Socket;
+
+public class Server{
+    public static void main(String[] args){
+        ServerSocket server = new ServerSocket(80);
+
+        System.out.println("Server has started on 127.0.0.1:80.\r\nWaiting for a connection...");
+
+        Socket client = server.accept();
+
+        System.out.println("A client connected.");
+    }
+}
+ +

Socket

+ +

Methods:

+ + + +

OutputStream

+ +

Methods:

+ +
write(byte[] b, int off, int len)
+ +

Writes len bytes from the specified byte array starting at offset off to this output stream.

+ +

InputStream

+ +

Methods:

+ +
read(byte[] b, int off, int len)
+ +

Reads up to len bytes of data from the input stream into an array of bytes.

+ +

Let us extend our example.

+ +
Socket client = server.accept();
+
+System.out.println("A client connected.");
+
+InputStream in = client.getInputStream();
+
+OutputStream out = client.getOutputStream();
+
+new Scanner(in, "UTF-8").useDelimiter("\\r\\n\\r\\n").next();
+ +

Handshaking

+ +

When a client connects to a server, it sends a GET request to upgrade the connection to a WebSocket from a simple HTTP request. This is known as handshaking.

+ +
import java.util.Scanner;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+//translate bytes of request to string
+String data = new Scanner(in,"UTF-8").useDelimiter("\\r\\n\\r\\n").next();
+
+Matcher get = Pattern.compile("^GET").matcher(data);
+
+if (get.find()) {
+
+} else {
+
+}
+ +

Creating the response is easier than understanding why you must do it in this way.

+ +

You must,

+ +
    +
  1. Obtain the value of Sec-WebSocket-Key request header without any leading and trailing whitespace
  2. +
  3. Link it with "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
  4. +
  5. Compute SHA-1 and Base64 code of it
  6. +
  7. Write it back as value of Sec-WebSocket-Accept response header as part of a HTTP response.
  8. +
+ +
if (get.find()) {
+    Matcher match = Pattern.compile("Sec-WebSocket-Key: (.*)").matcher(data);
+    match.find();
+    byte[] response = ("HTTP/1.1 101 Switching Protocols\r\n"
+            + "Connection: Upgrade\r\n"
+            + "Upgrade: websocket\r\n"
+            + "Sec-WebSocket-Accept: "
+            + DatatypeConverter
+            .printBase64Binary(
+                    MessageDigest
+                    .getInstance("SHA-1")
+                    .digest((match.group(1) + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11")
+                            .getBytes("UTF-8")))
+            + "\r\n\r\n")
+            .getBytes("UTF-8");
+
+    out.write(response, 0, response.length);
+}
+
+ +

Decoding messages

+ +

After a successful handshake, client can send messages to the server, but now these are encoded.

+ +

If we send "abcdef", we get these bytes:

+ + + + + + + + + + + + + + + + + + +
129134167225225210198131130182194135
+ +

- 129:

+ + + + + + + + + + + + + + + + + + + + +
FIN (Is this the whole message?)RSV1RSV2RSV3Opcode
10000x1=0001
+ +

FIN: You can send your message in frames, but now keep things simple.
+ Opcode 0x1 means this is a text. Full list of Opcodes

+ +

- 134:

+ +

If the second byte minus 128 is between 0 and 125, this is the length of the message. If it is 126, the following 2 bytes (16-bit unsigned integer), if 127, the following 8 bytes (64-bit unsigned integer, the most significant bit MUST be 0) are the length.

+ +
+

I can take 128 because the first bit is always 1.

+
+ +

- 167, 225, 225 and 210 are the bytes of the key to decode. It changes every time.

+ +

- The remaining encoded bytes are the message.

+ +

Decoding algorithm

+ +

decoded byte = encoded byte XOR (position of encoded byte BITWISE AND 0x3)th byte of key

+ +

Ví dụ trên Java:

+ +
byte[] decoded = new byte[6];
+byte[] encoded = new byte[] {198, 131, 130, 182, 194, 135};
+byte[] key = byte[4] {167, 225, 225, 210};
+
+for (int i = 0; i < encoded.length; i++) {
+    decoded[i] = (byte)(encoded[i] ^ key[i & 0x3]);
+}
+ +

Tài liệu liên quan

+ + + +
 
diff --git a/files/vi/web/api/window/index.html b/files/vi/web/api/window/index.html new file mode 100644 index 0000000000..1419252c54 --- /dev/null +++ b/files/vi/web/api/window/index.html @@ -0,0 +1,729 @@ +--- +title: Window +slug: Web/API/Window +tags: + - API + - Browser + - DOM + - Interface + - JavaScript + - NeedsTranslation + - Reference + - Tab + - TopicStub + - Window + - global + - global scope + - scope +translation_of: Web/API/Window +--- +
{{APIRef("DOM")}}
+ +

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

+ +

A global variable, window, representing the window in which the script is running, is exposed to JavaScript code.

+ +

The Window interface is home to a variety of functions, namespaces, objects, and constructors which are not necessarily directly associated with the concept of a user interface window. However, the Window interface is a suitable place to include these items that need to be globally available. Many of these are documented in the JavaScript Reference and the DOM Reference.

+ +

In a tabbed browser, each tab is represented by its own Window object; the global window seen by JavaScript code running within a given tab always represents the tab in which the code is running. That said, even in a tabbed browser, some properties and methods still apply to the overall window that contains the tab, such as {{Domxref("Window.resizeTo", "resizeTo()")}} and {{Domxref("Window.innerHeight", "innerHeight")}}. Generally, anything that can't reasonably pertain to a tab pertains to the window instead.

+ +

{{InheritanceDiagram}}

+ +

Constructors

+ +

See also the DOM Interfaces.

+ +
+
{{domxref("DOMParser")}}
+
DOMParser can parse XML or HTML source stored in a string into a DOM Document. DOMParser is specified in DOM Parsing and Serialization.
+
{{domxref("Window.GeckoActiveXObject")}}
+
{{todo("NeedsContents")}}
+
{{domxref("Image")}}
+
Used for creating an {{domxref("HTMLImageElement")}}.
+
{{domxref("Option")}}
+
Used for creating an {{domxref("HTMLOptionElement")}}
+
{{domxref("Window.QueryInterface")}}
+
{{todo("NeedsContents")}}
+
{{domxref("Window.StaticRange")}} {{experimental_inline}} {{readonlyinline}}
+
Returns a {{domxref('StaticRange.StaticRange','StaticRange()')}} constructor which creates a {{domxref('StaticRange')}} object.
+
{{domxref("Worker")}}
+
Used for creating a Web worker
+
{{domxref("Window.XMLSerializer")}}
+
{{todo("NeedsContents")}}
+
{{domxref("Window.XPCNativeWrapper")}}
+
{{todo("NeedsContents")}}
+
{{domxref("Window.XPCSafeJSObjectWrapper")}}
+
{{todo("NeedsContents")}}
+
+ +

Properties

+ +

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

+ +

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

+ +
+
{{domxref("Window.closed")}} {{Non-standard_inline}} {{readOnlyInline}}
+
This property indicates whether the current window is closed or not.
+
{{domxref("Window.console")}} {{ReadOnlyInline}}
+
Returns a reference to the console object which provides access to the browser's debugging console.
+
{{domxref("Window.content")}} and Window._content {{Non-standard_inline}} {{obsolete_inline}} {{ReadOnlyInline}}
+
Returns a reference to the content element in the current window. Since Firefox 57 (initially Nightly-only), both versions are only available from chrome (privileged) code, and not available to the web anymore.
+
{{domxref("Window.controllers")}} {{non-standard_inline}} {{ReadOnlyInline}}
+
Returns the XUL controller objects for the current chrome window.
+
{{domxref("Window.customElements")}} {{ReadOnlyInline}}
+
returns a reference to the {{domxref("CustomElementRegistry")}} object, which can be used to register new custom elements and get information about previously registered custom elements.
+
{{domxref("Window.crypto")}} {{readOnlyInline}}
+
Returns the browser crypto object.
+
{{domxref("Window.defaultStatus")}} {{Obsolete_inline("gecko23")}}
+
Gets/sets the status bar text for the given window.
+
{{domxref("Window.devicePixelRatio")}} {{non-standard_inline}} {{ReadOnlyInline}}
+
Returns the ratio between physical pixels and device independent pixels in the current display.
+
{{domxref("Window.dialogArguments")}} {{Fx_minversion_inline(3)}} {{ReadOnlyInline}}
+
Gets the arguments passed to the window (if it's a dialog box) at the time {{domxref("window.showModalDialog()")}} was called. This is an {{Interface("nsIArray")}}.
+
{{domxref("Window.directories")}} {{obsolete_inline}}
+
Synonym of {{domxref("window.personalbar")}}
+
{{domxref("Window.document")}} {{ReadOnlyInline}}
+
Returns a reference to the document that the window contains.
+
{{domxref("Window.DOMMatrix")}} {{readOnlyInline}} {{experimental_inline}}
+
Returns a reference to a {{domxref("DOMMatrix")}} object, which represents 4x4 matrices, suitable for 2D and 3D operations.
+
{{domxref("Window.DOMMatrixReadOnly")}} {{readOnlyInline}} {{experimental_inline}}
+
Returns a reference to a {{domxref("DOMMatrixReadOnly")}} object, which represents 4x4 matrices, suitable for 2D and 3D operations.
+
{{domxref("Window.DOMPoint")}} {{readOnlyInline}} {{experimental_inline}}
+
Returns a reference to a {{domxref("DOMPoint")}} object, which represents a 2D or 3D point in a coordinate system.
+
{{domxref("Window.DOMPointReadOnly")}} {{readOnlyInline}} {{experimental_inline}}
+
Returns a reference to a {{domxref("DOMPointReadOnly")}} object, which represents a 2D or 3D point in a coordinate system.
+
{{domxref("Window.DOMQuad")}} {{readOnlyInline}} {{experimental_inline}}
+
Returns a reference to a {{domxref("DOMQuad")}} object, which provides represents a quadrilaterial object, that is one having four corners and four sides.
+
{{domxref("Window.DOMRect")}} {{readOnlyInline}} {{experimental_inline}}
+
Returns a reference to a {{domxref("DOMRect")}} object, which represents a rectangle.
+
{{domxref("Window.DOMRectReadOnly")}} {{readOnlyInline}} {{experimental_inline}}
+
Returns a reference to a {{domxref("DOMRectReadOnly")}} object, which represents a rectangle.
+
{{domxref("Window.event")}} {{ReadOnlyInline}}
+
Returns the current event, which is the event currently being handled by the JavaScript code's context, or undefined if no event is currently being handled. The {{domxref("Event")}} object passed directly to event handlers should be used instead whenever possible.
+
{{domxref("Window.frameElement")}} {{readOnlyInline}}
+
Returns the element in which the window is embedded, or null if the window is not embedded.
+
{{domxref("Window.frames")}} {{readOnlyInline}}
+
Returns an array of the subframes in the current window.
+
{{domxref("Window.fullScreen")}} {{gecko_minversion_inline("1.9")}}
+
This property indicates whether the window is displayed in full screen or not.
+
{{domxref("Window.globalStorage")}} {{gecko_minversion_inline("1.8.1")}} {{Non-standard_inline}} {{Obsolete_inline("gecko13")}}
+
Unsupported since Gecko 13 (Firefox 13). Use {{domxref("Window.localStorage")}} instead.
+ Was: Multiple storage objects that are used for storing data across multiple pages.
+
{{domxref("Window.history")}} {{ReadOnlyInline}}
+
Returns a reference to the history object.
+
{{domxref("Window.innerHeight")}} {{readOnlyInline}}
+
Gets the height of the content area of the browser window including, if rendered, the horizontal scrollbar.
+
{{domxref("Window.innerWidth")}} {{readOnlyInline}}
+
Gets the width of the content area of the browser window including, if rendered, the vertical scrollbar.
+
{{domxref("Window.isSecureContext")}} {{experimental_inline}} {{readOnlyInline}}
+
Indicates whether a context is capable of using features that require secure contexts.
+
{{domxref("Window.length")}} {{readOnlyInline}}
+
Returns the number of frames in the window. See also {{domxref("window.frames")}}.
+
{{domxref("Window.location")}}
+
Gets/sets the location, or current URL, of the window object.
+
{{domxref("Window.locationbar")}} {{ReadOnlyInline}}
+
Returns the locationbar object, whose visibility can be toggled in the window.
+
{{domxref("Window.localStorage")}} {{readOnlyInline}} {{gecko_minversion_inline("1.9.1")}}
+
Returns a reference to the local storage object used to store data that may only be accessed by the origin that created it.
+
{{domxref("Window.menubar")}} {{ReadOnlyInline}}
+
Returns the menubar object, whose visibility can be toggled in the window.
+
{{domxref("Window.messageManager")}} {{gecko_minversion_inline("2.0")}}
+
Returns the message manager object for this window.
+
{{domxref("Window.mozAnimationStartTime")}} {{ReadOnlyInline}} {{gecko_minversion_inline("2.0")}} {{Deprecated_inline}}
+
The time in milliseconds since epoch at which the current animation cycle began. Use {{domxref("Animation.startTime")}} instead.
+
{{domxref("Window.mozInnerScreenX")}} {{ReadOnlyInline}} {{non-standard_inline}} {{gecko_minversion_inline("1.9.2")}}
+
Returns the horizontal (X) coordinate of the top-left corner of the window's viewport, in screen coordinates. This value is reported in CSS pixels. See mozScreenPixelsPerCSSPixel in {{interface("nsIDOMWindowUtils")}} for a conversion factor to adapt to screen pixels if needed.
+
{{domxref("Window.mozInnerScreenY")}} {{ReadOnlyInline}} {{non-standard_inline}} {{gecko_minversion_inline("1.9.2")}}
+
Returns the vertical (Y) coordinate of the top-left corner of the window's viewport, in screen coordinates. This value is reported in CSS pixels. See mozScreenPixelsPerCSSPixel for a conversion factor to adapt to screen pixels if needed.
+
{{domxref("Window.mozPaintCount")}} {{non-standard_inline}} {{ReadOnlyInline}} {{gecko_minversion_inline("2.0")}}
+
Returns the number of times the current document has been rendered to the screen in this window. This can be used to compute rendering performance.
+
{{domxref("Window.name")}}
+
Gets/sets the name of the window.
+
{{domxref("Window.navigator")}} {{readOnlyInline}}
+
Returns a reference to the navigator object.
+
{{domxref("Window.opener")}}
+
Returns a reference to the window that opened this current window.
+
{{domxref("Window.orientation")}} {{non-standard_inline}} {{deprecated_inline}} {{readOnlyInline}}
+
Returns the orientation in degrees (in 90 degree increments) of the viewport relative to the device's natural orientation.
+
{{domxref("Window.outerHeight")}} {{readOnlyInline}}
+
Gets the height of the outside of the browser window.
+
{{domxref("Window.outerWidth")}} {{readOnlyInline}}
+
Gets the width of the outside of the browser window.
+
{{domxref("Window.scrollX","Window.pageXOffset")}} {{readOnlyInline}}
+
An alias for {{domxref("window.scrollX")}}.
+
{{domxref("Window.scrollY","Window.pageYOffset")}} {{readOnlyInline}}
+
An alias for {{domxref("window.scrollY")}}
+
{{domxref("Window.parent")}} {{readOnlyInline}}
+
Returns a reference to the parent of the current window or subframe.
+
{{domxref("Window.performance")}} {{readOnlyInline}}
+
Returns a {{domxref("Performance")}} object, which includes the {{domxref("Performance.timing", "timing")}} and {{domxref("Performance.navigation", "navigation")}} attributes, each of which is an object providing performance-related data. See also Using Navigation Timing for additional information and examples.
+
{{domxref("Window.personalbar")}} {{readOnlyInline}}
+
Returns the personalbar object, whose visibility can be toggled in the window.
+
{{domxref("Window.pkcs11")}} {{obsolete_inline(29)}}
+
Formerly provided access to install and remove PKCS11 modules.
+
{{domxref("Window.returnValue")}} {{Fx_minversion_inline(3)}}
+
The return value to be returned to the function that called {{domxref("window.showModalDialog()")}} to display the window as a modal dialog.
+
{{domxref("Window.screen")}} {{readOnlyInline}}
+
Returns a reference to the screen object associated with the window.
+
{{domxref("Window.screenX")}} and {{domxref("Window.screenLeft")}} {{readOnlyInline}}
+
Both properties return the horizontal distance from the left border of the user's browser viewport to the left side of the screen.
+
{{domxref("Window.screenY")}} and {{domxref("Window.screenTop")}} {{readOnlyInline}}
+
Both properties return the vertical distance from the top border of the user's browser viewport to the top side of the screen.
+
{{domxref("Window.scrollbars")}} {{readOnlyInline}}
+
Returns the scrollbars object, whose visibility can be toggled in the window.
+
{{domxref("Window.scrollMaxX")}} {{non-standard_inline}} {{ReadOnlyInline}}
+
The maximum offset that the window can be scrolled to horizontally, that is the document width minus the viewport width.
+
{{domxref("Window.scrollMaxY")}} {{non-standard_inline}} {{ReadOnlyInline}}
+
The maximum offset that the window can be scrolled to vertically (i.e., the document height minus the viewport height).
+
{{domxref("Window.scrollX")}} {{readOnlyInline}}
+
Returns the number of pixels that the document has already been scrolled horizontally.
+
{{domxref("Window.scrollY")}} {{readOnlyInline}}
+
Returns the number of pixels that the document has already been scrolled vertically.
+
{{domxref("Window.self")}} {{ReadOnlyInline}}
+
Returns an object reference to the window object itself.
+
{{domxref("Window.sessionStorage")}}
+
Returns a reference to the session storage object used to store data that may only be accessed by the origin that created it.
+
{{domxref("Window.sidebar")}} {{non-standard_inline}} {{ReadOnlyInline}}
+
Returns a reference to the window object of the sidebar.
+
{{domxref("Window.speechSynthesis")}} {{ReadOnlyInline}}
+
Returns a {{domxref("SpeechSynthesis")}} object, which is the entry point into using Web Speech API speech synthesis functionality.
+
{{domxref("Window.status")}}
+
Gets/sets the text in the statusbar at the bottom of the browser.
+
{{domxref("Window.statusbar")}} {{readOnlyInline}}
+
Returns the statusbar object, whose visibility can be toggled in the window.
+
{{domxref("Window.toolbar")}} {{readOnlyInline}}
+
Returns the toolbar object, whose visibility can be toggled in the window.
+
{{domxref("Window.top")}} {{readOnlyInline}}
+
Returns a reference to the topmost window in the window hierarchy. This property is read only.
+
{{domxref("Window.visualViewport")}} {{readOnlyInline}}
+
Returns a {{domxref("VisualViewport")}} object which represents the visual viewport for a given window.
+
{{domxref("Window.window")}} {{ReadOnlyInline}}
+
Returns a reference to the current window.
+
window[0], window[1], etc.
+
Returns a reference to the window object in the frames. See {{domxref("Window.frames")}} for more details.
+
+ +

Properties implemented from elsewhere

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

Methods

+ +

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

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

Methods implemented from elsewhere

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

Obsolete methods

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

Event handlers

+ +

These are properties of the window object that can be set to establish event handlers for the various things that can happen in the window that might be of interest.

+ +

This interface inherits event handlers from the {{domxref("EventTarget")}} interface and implements event handlers from {{domxref("WindowEventHandlers")}}.

+ +
+

Note: Starting in {{Gecko("9.0")}}, you can now use the syntax if ("onabort" in window) to determine whether or not a given event handler property exists. This is because event handler interfaces have been updated to be proper web IDL interfaces. See DOM event handlers for details.

+
+ +
+
{{domxref("Window.onappinstalled")}}
+
Called when the page is installed as a webapp. See {{event('appinstalled')}} event.
+
{{domxref("Window.onbeforeinstallprompt")}}
+
An event handler property dispatched before a user is prompted to save a web site to a home screen on mobile.
+
{{domxref("Window.ondevicelight")}}
+
An event handler property for any ambient light levels changes
+
{{domxref("Window.ondevicemotion")}} {{gecko_minversion_inline("6.0")}}
+
Called if accelerometer detects a change (For mobile devices)
+
{{domxref("Window.ondeviceorientation")}} {{gecko_minversion_inline("6.0")}}
+
Called when the orientation is changed (For mobile devices)
+
{{domxref("Window.ondeviceorientationabsolute")}} {{non-standard_inline}} Chrome only
+
An event handler property for any device orientation changes.
+
{{domxref("Window.ondeviceproximity")}}
+
An event handler property for device proximity event
+
{{domxref("Window.ongamepadconnected")}}
+
Represents an event handler that will run when a gamepad is connected (when the {{event('gamepadconnected')}} event fires).
+
{{domxref("Window.ongamepaddisconnected")}}
+
Represents an event handler that will run when a gamepad is disconnected (when the {{event('gamepaddisconnected')}} event fires).
+
{{domxref("Window.onmozbeforepaint")}} {{gecko_minversion_inline("2.0")}}
+
An event handler property for the MozBeforePaint event, which is sent before repainting the window if the event has been requested by a call to the {{domxref("Window.mozRequestAnimationFrame()")}} method.
+
{{domxref("Window.onpaint")}}
+
An event handler property for paint events on the window.
+
{{domxref("Window.onrejectionhandled")}} {{experimental_inline}}
+
An event handler for handled {{jsxref("Promise")}} rejection events.
+
{{domxref("Window.onuserproximity")}}
+
An event handler property for user proximity events.
+
{{domxref("Window.onvrdisplayconnect")}}
+
Represents an event handler that will run when a compatible VR device has been connected to the computer (when the {{event("vrdisplayconnected")}} event fires).
+
{{domxref("Window.onvrdisplaydisconnect")}}
+
Represents an event handler that will run when a compatible VR device has been disconnected from the computer (when the {{event("vrdisplaydisconnected")}} event fires).
+
{{domxref("Window.onvrdisplayactivate")}}
+
Represents an event handler that will run when a display is able to be presented to (when the {{event("vrdisplayactivate")}} event fires), for example if an HMD has been moved to bring it out of standby, or woken up by being put on.
+
{{domxref("Window.onvrdisplaydeactivate")}}
+
Represents an event handler that will run when a display can no longer be presented to (when the {{event("vrdisplaydeactivate")}} event fires), for example if an HMD has gone into standby or sleep mode due to a period of inactivity.
+
{{domxref("Window.onvrdisplayblur")}}
+
Represents an event handler that will run when presentation to a display has been paused for some reason by the browser, OS, or VR hardware (when the {{event("vrdisplayblur")}} event fires) — for example, while the user is interacting with a system menu or browser, to prevent tracking or loss of experience.
+
{{domxref("Window.onvrdisplayfocus")}}
+
Represents an event handler that will run when presentation to a display has resumed after being blurred (when the {{event("vrdisplayfocus")}} event fires).
+
{{domxref("Window.onvrdisplaypresentchange")}}
+
represents an event handler that will run when the presenting state of a VR device changes — i.e. goes from presenting to not presenting, or vice versa (when the {{event("vrdisplaypresentchange")}} event fires).
+
+ +

Event handlers implemented from elsewhere

+ +
+
{{domxref("GlobalEventHandlers.onabort")}}
+
Called when the loading of a resource has been aborted, such as by a user canceling the load while it is still in progress
+
{{domxref("WindowEventHandlers.onafterprint")}}
+
Called when the print dialog box is closed. See {{event("afterprint")}} event.
+
{{domxref("WindowEventHandlers.onbeforeprint")}}
+
Called when the print dialog box is opened. See {{event("beforeprint")}} event.
+
{{domxref("WindowEventHandlers.onbeforeunload")}}
+
An event handler property for before-unload events on the window.
+
{{domxref("GlobalEventHandlers.onblur")}}
+
Called after the window loses focus, such as due to a popup.
+
{{domxref("GlobalEventHandlers.onchange")}}
+
An event handler property for change events on the window.
+
{{domxref("GlobalEventHandlers.onclick")}}
+
Called after the ANY mouse button is pressed & released
+
{{domxref("GlobalEventHandlers.ondblclick")}}
+
Called when a double click is made with ANY mouse button.
+
{{domxref("GlobalEventHandlers.onclose")}}
+
Called after the window is closed
+
{{domxref("GlobalEventHandlers.oncontextmenu")}}
+
Called when the RIGHT mouse button is pressed
+
{{domxref("GlobalEventHandlers.onerror")}}
+
Called when a resource fails to load OR when an error occurs at runtime. See {{event("error")}} event.
+
{{domxref("GlobalEventHandlers.onfocus")}}
+
Called after the window receives or regains focus. See {{event("focus")}} events.
+
{{domxref("WindowEventHandlers.onhashchange")}} {{gecko_minversion_inline("1.9.2")}}
+
An event handler property for {{event('hashchange')}} events on the window; called when the part of the URL after the hash mark ("#") changes.
+
{{domxref("GlobalEventHandlers.oninput")}}
+
Called when the value of an <input> element changes
+
{{domxref("GlobalEventHandlers.onkeydown")}}
+
Called when you begin pressing ANY key. See {{event("keydown")}} event.
+
{{domxref("GlobalEventHandlers.onkeypress")}}
+
Called when a key (except Shift, Fn, and CapsLock) is in pressed position. See {{event("keypress")}} event.
+
{{domxref("GlobalEventHandlers.onkeyup")}}
+
Called when you finish releasing ANY key. See {{event("keyup")}} event.
+
{{domxref("WindowEventHandlers.onlanguagechange")}}
+
An event handler property for {{event("languagechange")}} events on the window.
+
{{domxref("GlobalEventHandlers.onload")}}
+
Called after all resources and the DOM are fully loaded. WILL NOT get called when the page is loaded from cache, such as with back button.
+
{{domxref("WindowEventHandlers.onmessage")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("message")}} event is raised.
+
{{domxref("GlobalEventHandlers.onmousedown")}}
+
Called when ANY mouse button is pressed.
+
{{domxref("GlobalEventHandlers.onmousemove")}}
+
Called continously when the mouse is moved inside the window.
+
{{domxref("GlobalEventHandlers.onmouseout")}}
+
Called when the pointer leaves the window.
+
{{domxref("GlobalEventHandlers.onmouseover")}}
+
Called when the pointer enters the window
+
{{domxref("GlobalEventHandlers.onmouseup")}}
+
Called when ANY mouse button is released
+
{{domxref("WindowEventHandlers.onoffline")}}
+
Called when network connection is lost. See {{event("offline")}} event.
+
{{domxref("WindowEventHandlers.ononline")}}
+
Called when network connection is established. See {{event("online")}} event.
+
{{domxref("WindowEventHandlers.onpagehide")}}
+
Called when the user navigates away from the page, before the onunload event. See {{event("pagehide")}} event.
+
{{domxref("WindowEventHandlers.onpageshow")}}
+
Called after all resources and the DOM are fully loaded. See {{event("pageshow")}} event.
+
{{domxref("WindowEventHandlers.onpopstate")}} {{gecko_minversion_inline("2.0")}}
+
Called when a back button is pressed.
+
{{domxref("GlobalEventHandlers.onreset")}}
+
Called when a form is reset
+
{{domxref("GlobalEventHandlers.onresize")}}
+
Called continuously as you are resizing the window.
+
{{domxref("GlobalEventHandlers.onscroll")}}
+
Called when the scroll bar is moved via ANY means. If the resource fully fits in the window, then this event cannot be invoked
+
{{domxref("GlobalEventHandlers.onwheel")}}
+
Called when the mouse wheel is rotated around any axis
+
{{domxref("GlobalEventHandlers.onselect")}}
+
Called after text in an input field is selected
+
{{domxref("GlobalEventHandlers.onselectionchange")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("selectionchange")}} event is raised.
+
{{domxref("WindowEventHandlers.onstorage")}}
+
Called when there is a change in session storage or local storage. See {{event("storage")}} event
+
{{domxref("GlobalEventHandlers.onsubmit")}}
+
Called when a form is submitted
+
{{domxref("WindowEventHandlers.onunhandledrejection")}} {{experimental_inline}}
+
An event handler for unhandled {{jsxref("Promise")}} rejection events.
+
{{domxref("WindowEventHandlers.onunload")}}
+
Called when the user navigates away from the page.
+
+ +

Events

+ +

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

+ +
+
error
+
Fired when when a resource failed to load, or can't be used. For example, if a script has an execution error or an image can't be found or is invalid.
+ Also available via the {{domxref("GlobalEventHandlers/onerror", "onerror")}} property.
+
languagechange
+
Fired at the global scope object when the user's preferred language changes.
+ Also available via the onlanguagechange property.
+
orientationchange
+
Fired when the orientation of the device has changed.
+ Also available via the onorientationchange property.
+
devicemotion
+
Fired at a regular interval, indicating the amount of physical force of acceleration the device is receiving and the rate of rotation, if available.
+
deviceorientation
+
Fired when fresh data is available from the magnetometer orientation sensor about the current orientation of the device as compared to the Earth coordinate frame.
+
{{domxref("Document/defaultView/resize_event", "resize")}}
+
Fired when the window has been resized.
+ Also available via the onresize property.
+
{{domxref("Document/defaultView/storage_event", "storage")}}
+
Fired when a storage area (localStorage or sessionStorage) has been modified in the context of another document.
+ Also available via the onstorage property.
+
+ +

Animation events

+ +
+
animationcancel
+
Fired when an animation unexpectedly aborts.
+ Also available via the onanimationcancel property.
+
animationend
+
Fired when an animation has completed normally.
+ Also available via the onanimationend property.
+
animationiteration
+
Fired when an animation iteration has completed.
+ Also available via the onanimationiteration property.
+
animationstart
+
Fired when an animation starts.
+ Also available via the onanimationstart property.
+
+ +

Clipboard events

+ +
+
clipboardchange
+
Fired when the system clipboard content changes.
+
copy
+
Fired when the user initiates a copy action through the browser's user interface.
+ Also available via the oncopy property.
+
cut
+
Fired when the user initiates a cut action through the browser's user interface.
+ Also available via the oncut property.
+
paste
+
Fired when the user initiates a paste action through the browser's user interface.
+ Also available via the onpaste property.
+
+ +

Connection events

+ +
+
offline
+
Fired when the browser has lost access to the network and the value of navigator.onLine has switched to false.
+ Also available via the {{domxref("WindowEventHandlers.onoffline", "onoffline")}} property.
+
online
+
Fired when the browser has gained access to the network and the value of navigator.onLine has switched to true.
+ Also available via the {{domxref("WindowEventHandlers.ononline", "ononline")}} property.
+
+ +

Focus events

+ +
+
blur
+
Fired when an element has lost focus.
+ Also available via the onblur property.
+
focus
+
Fired when an element has gained focus.
+ Also available via the onfocus property
+
+ +

Gamepad events

+ +
+
gamepadconnected
+
Fired when the browser detects that a gamepad has been connected or the first time a button/axis of the gamepad is used.
+ Also available via the ongamepadconnected property.
+
gamepaddisconnected
+
Fired when the browser detects that a gamepad has been disconnected.
+ Also available via the ongamepaddisconnected property
+
+ +

History events

+ +
+
hashchange
+
Fired when the fragment identifier of the URL has changed (the part of the URL beginning with and following the # symbol).
+ Also available via the onhashchange property.
+
pagehide
+
Sent when the browser  hides the current document while in the process of switching to displaying in its palce a different document from the session's history. This happens, for example, when the user clicks the Back button or when they click the Forward button to move ahead in session history.
+ Also available through the onpagehide event handler property.
+
pageshow
+
Sent when the browser makes the document visible due to navigation tasks, including not only when the page is first loaded, but also situations such as the user navigating back to the page after having navigated to another within the same tab.
+ Also available using the onpageshow event handler property.
+
{{domxref("Document/defaultView/popstate_event", "popstate")}}
+
Fired when the active history entry changes.
+ Also available using the onpopstate event handler property.
+
+ +

Load & unload events

+ +
+
beforeunload
+
Fired when the window, the document and its resources are about to be unloaded.
+ Also available via the onbeforeunload property.
+
DOMContentLoaded
+
Fired when the document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading.
+
load
+
Fired when the whole page has loaded, including all dependent resources such as stylesheets images.
+ Also available via the onload property.
+
unload
+
Fired when the document or a child resource is being unloaded.
+ Also available via the onunload property.
+
+ +

Manifest events

+ +
+
appinstalled
+
Fired when the browser has successfully installed a page as an application.
+ Also available via the onappinstalled property.
+
beforeinstallprompt
+
Fired when a user is about to be prompted to install a web application.
+ Also available via the onbeforeinstallprompt property.
+
+ +

Messaging events

+ +
+
message
+
Fired when the window receives a message, for example from a call to Window.postMessage() from another browsing context.
+ Also available via the onmessage property.
+
messageerror
+
Fired when a Window object receives a message that can't be deserialized.
+ Also available via the onmessageerror property.
+
+ + + +
+
afterprint
+
Fired after the associated document has started printing or the print preview has been closed.
+ Also available via the onafterprint property.
+
beforeprint
+
Fired when the associated document is about to be printed or previewed for printing.
+ Also available via the onbeforeprint property.
+
+ +

Promise rejection events

+ +
+
rejectionhandled
+
Sent every time a JavaScript {{jsxref("Promise")}} is rejected, regardless of whether or not there is a handler in place to catch the rejection.
+ Also available through the onrejectionhandled event handler property.
+
unhandledrejection
+
Sent when a JavaScript {{jsxref("Promise")}} is rejected but there is no handler in place to catch the rejection.
+ Also available using the onunhandledrejection event handler property.
+
+ +

Transition events

+ +
+
transitioncancel
+
Fired when a CSS transition is canceled.
+ Also available via the ontransitioncancel property.
+
transitionend
+
Fired when a CSS transition has completed.
+ Also available via the ontransitionend property.
+
transitionrun
+
Fired when a CSS transition is first created.
+ Also available via the ontransitionrun property.
+
transitionstart
+
Fired when a CSS transition has actually started.
+ Also available via the ontransitionstart property.
+
+ +

WebVR events

+ +
+
vrdisplayactivate
+
Fired when a VR display becomes available to be presented to, for example if an HMD has been moved to bring it out of standby, or woken up by being put on.
+ Also available via the onvrdisplayactivate property.
+
vrdisplayblur
+
Fired when presentation to a VR display has been paused for some reason by the browser, OS, or VR hardware.
+ Also available via the onvrdisplayblur property.
+
vrdisplayconnect
+
Fired when a compatible VR display is connected to the computer.
+ Also available via the onvrdisplayconnect property.
+
vrdisplaydeactivate
+
Fired when a VR display can no longer be presented to, for example if an HMD has gone into standby or sleep mode due to a period of inactivity.
+ Also available via the onvrdisplaydeactivate property.
+
vrdisplaydisconnect
+
Fired when a compatible VR display is disconnected from the computer.
+ Also available via the onvrdisplaydisconnect property.
+
vrdisplayfocus
+
Fired when presentation to a VR display has resumed after being blurred.
+ Also available via the onvrdisplayfocus property.
+
vrdisplaypresentchange
+
fired when the presenting state of a VR display changes — i.e. goes from presenting to not presenting, or vice versa.
+ Also available via the onvrdisplaypresentchange property.
+
vrdisplaypointerrestricted
+
Fired when the VR display's pointer input is restricted to consumption via a pointerlocked element.
+ Also available via the onvrdisplaypointerrestricted property.
+
vrdisplaypointerunrestricted
+
Fired when the VR display's pointer input is no longer restricted to consumption via a pointerlocked element.
+ Also available via the onvrdisplaypointerunrestricted property.
+
+ +

Interfaces

+ +

See DOM Reference

+ +

Browser compatibility

+ + + +

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

+ +

See also

+ + diff --git a/files/vi/web/api/window/prompt/index.html b/files/vi/web/api/window/prompt/index.html new file mode 100644 index 0000000000..9830f0cb7c --- /dev/null +++ b/files/vi/web/api/window/prompt/index.html @@ -0,0 +1,86 @@ +--- +title: Window.prompt() +slug: Web/API/Window/prompt +translation_of: Web/API/Window/prompt +--- +
{{ApiRef("Window")}}
+ +

Câu lệnh Window.prompt() hiển thị một cửa sổ yêu cầu người dùng nhập liệu vào.

+ +

Cú pháp

+ +
result = window.prompt(message, default);
+
+ +

Các tham số

+ +
+
message {{optional_inline}}
+
Là một dòng thông báo hiện ra cho người dùng xem. Có thể bỏ trống không cần nhập.
+
default {{optional_inline}}
+
Là giá trị mặc định hiển thị ở khung nhập liệu. Lưu ý nếu bạn dùng Internet Explorer 7 hoặc 8, nếu không cung cấp tham số này, thì giá trị mặc định sẽ là "undefined"
+
+ +

Giá trị trả về

+ +

Trả về chuỗi text hoặc null.

+ +

Example

+ +
let sign = prompt("What's your sign?");
+
+if (sign.toLowerCase() == "scorpio") {
+  alert("Wow! I'm a Scorpio too!");
+}
+
+// Có nhiều cách để sử dụng prompt()
+sign = window.prompt(); // open the blank prompt window
+sign = prompt();       //  open the blank prompt window
+sign = window.prompt('Are you feeling lucky'); // open the window with Text "Are you feeling lucky"
+sign = window.prompt('Are you feeling lucky', 'sure'); // open the window with Text "Are you feeling lucky" and default value "sure"
+ +

Khi người dùng ấn OK, giá trị họ nhập vào sẽ là giá trị trả về ở dạng chuỗi text. Nếu họ nhấn OK mà chưa nhập gì thì sẽ trả về chuỗi rỗng. Và nếu họ bấm Cancel thì sẽ trả về null.

+ +

Giao diện cửa sổ prompt (trình duyệt Chrome trên OS X):

+ +

prompt() dialog in Chrome on OS X

+ +

Các lưu ý

+ +

Cửa sổ prompt chứa 1 textbox một dòng, 1 nút OK và 1 nút Cancel, và trả về giá trị người dùng nhập vào (có thể rỗng).

+ +

The following text is shared between this article, DOM:window.confirm and DOM:window.alert Dialog boxes are modal windows; chúng sẽ ngăn người dùng truy cập vào các nội dung khác của website cho đến khi hoàn thành thao tác với cửa sổ prompt. Chính vì vậy, bạn không nên lạm dụng nó quá mức.

+ +

Giá trị trả về là chuỗi text, vì vậy nếu bạn muốn chắc chắn đó là kiểu Number thì hãy ép kiểu nó như ví dụ bên dưới:

+ +
const aNumber = Number(window.prompt("Type a number", ""));
+ +

Specification

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'timers-and-user-prompts.html#dom-prompt', 'prompt()')}}{{Spec2('HTML WHATWG')}}
+ +

Browser Compatibility

+ + + +

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

+ +

See also

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