From 074785cea106179cb3305637055ab0a009ca74f2 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:42:52 -0500 Subject: initial commit --- .../base64_encoding_and_decoding/index.html | 138 ++++++++++++++++++++ files/ru/web/api/windowbase64/btoa/index.html | 141 +++++++++++++++++++++ files/ru/web/api/windowbase64/index.html | 120 ++++++++++++++++++ 3 files changed, 399 insertions(+) create mode 100644 files/ru/web/api/windowbase64/base64_encoding_and_decoding/index.html create mode 100644 files/ru/web/api/windowbase64/btoa/index.html create mode 100644 files/ru/web/api/windowbase64/index.html (limited to 'files/ru/web/api/windowbase64') diff --git a/files/ru/web/api/windowbase64/base64_encoding_and_decoding/index.html b/files/ru/web/api/windowbase64/base64_encoding_and_decoding/index.html new file mode 100644 index 0000000000..b85f3671ef --- /dev/null +++ b/files/ru/web/api/windowbase64/base64_encoding_and_decoding/index.html @@ -0,0 +1,138 @@ +--- +title: Кодирование и декодирование в формате Base64 +slug: Web/API/WindowBase64/Base64_encoding_and_decoding +translation_of: Glossary/Base64 +--- +

Base64 - это группа cхожих binary-to-text encoding схем, которые представляют двоичные данные в ASCII-формате методом перевода в radix-64 представление. Термин Base64 происходит от a specific MIME content transfer encoding.

+ +

Кодирование Base64 широко используется в случаях, когда требуется перекодировать двоичные данные для передачи по каналу приспособленному для передачи текстовых данных. Это делается с целью защиты двоичных данных от любых возможных повреждений при передаче. Base64 широко используется во многих приложениях, включая электронную почту (MIME), и при сохранении больших объёмов данных в XML.

+ +

В языке JavaScript существуют две функции, для кодирования и декодирования данных в/из формат Base64 соответственно:

+ + + +

Функция atob() декодирует Base64-кодированную строку. В противоположность ей, функция btoa() создаёт Base64 кодированную ASCII строку из "строки" бинарных данных.

+ +

Обе функции atob() и btoa() работают со строками. Если вам необходимо работать с ArrayBuffers, обратитесь к этому параграфу.

+ + + + + + + + +
+

Документация

+ +
+
data URIs
+
data URIs, описанные в RFC 2397, позволяют создателям контента встроить в документ маленькие файлы в виде строки (инлайном).
+
Base64
+
Wikipedia article about Base64 encoding.
+
{{domxref("WindowBase64.atob","atob()")}}
+
Decodes a string of data which has been encoded using base-64 encoding.
+
{{domxref("WindowBase64.btoa","btoa()")}}
+
Creates a base-64 encoded ASCII string from a "string" of binary data.
+
The "Unicode Problem"
+
In most browsers, calling btoa() on a Unicode string will cause a Character Out Of Range exception. This paragraph shows some solutions.
+
URIScheme
+
List of Mozilla supported URI schemes
+
StringView
+
In this article is published a library of ours whose aims are: +
    +
  • creating a C-like interface for strings (i.e. array of characters codes — ArrayBufferView in JavaScript) based upon the JavaScript ArrayBuffer interface,
  • +
  • creating a collection of methods for such string-like objects (since now: stringViews) which work strictly on array of numbers rather than on immutable JavaScript strings,
  • +
  • working with other Unicode encodings, different from default JavaScript's UTF-16 DOMStrings,
  • +
+
+
+ +

View All...

+
+

Tools

+ + + +

View All...

+ + + + +
+ +

The "Unicode Problem"

+ +

Since DOMStrings are 16-bit-encoded strings, in most browsers calling window.btoa on a Unicode string will cause a Character Out Of Range exception if a character exceeds the range of a 8-bit byte (0x00~0xFF). There are two possible methods to solve this problem:

+ + + +

Here are the two possible methods.

+ +

Solution #1 – escaping the string before encoding it

+ +
function b64EncodeUnicode(str) {
+    // first we use encodeURIComponent to get percent-encoded UTF-8,
+    // then we convert the percent encodings into raw bytes which
+    // can be fed into btoa.
+    return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g,
+        function toSolidBytes(match, p1) {
+            return String.fromCharCode('0x' + p1);
+    }));
+}
+
+b64EncodeUnicode('✓ à la mode'); // "4pyTIMOgIGxhIG1vZGU="
+b64EncodeUnicode('\n'); // "Cg=="
+
+ +

To decode the Base64-encoded value back into a String:

+ +
function b64DecodeUnicode(str) {
+    // Going backwards: from bytestream, to percent-encoding, to original string.
+    return decodeURIComponent(atob(str).split('').map(function(c) {
+        return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
+    }).join(''));
+}
+
+b64DecodeUnicode('4pyTIMOgIGxhIG1vZGU='); // "✓ à la mode"
+b64DecodeUnicode('Cg=='); // "\n"
+
+ +

Unibabel implements common conversions using this strategy.

+ +

Solution #2 – rewrite the DOMs atob() and btoa() using JavaScript's TypedArrays and UTF-8

+ +

Use a TextEncoder polyfill such as TextEncoding (also includes legacy windows, mac, and ISO encodings), TextEncoderLite, combined with a Buffer and a Base64 implementation such as base64-js.

+ +

When a native TextEncoder implementation is not available, the most light-weight solution would be to use TextEncoderLite with base64-js. Use the browser implementation when you can.

+ +

The following function implements such a strategy. It assumes base64-js imported as <script type="text/javascript" src="base64js.min.js"/>. Note that TextEncoderLite only works with UTF-8.

+ +
function Base64Encode(str, encoding = 'utf-8') {
+    var bytes = new (TextEncoder || TextEncoderLite)(encoding).encode(str);
+    return base64js.fromByteArray(bytes);
+}
+
+function Base64Decode(str, encoding = 'utf-8') {
+    var bytes = base64js.toByteArray(str);
+    return new (TextDecoder || TextDecoderLite)(encoding).decode(bytes);
+}
+
diff --git a/files/ru/web/api/windowbase64/btoa/index.html b/files/ru/web/api/windowbase64/btoa/index.html new file mode 100644 index 0000000000..06b76a6304 --- /dev/null +++ b/files/ru/web/api/windowbase64/btoa/index.html @@ -0,0 +1,141 @@ +--- +title: WindowBase64.btoa() +slug: Web/API/WindowBase64/btoa +translation_of: Web/API/WindowOrWorkerGlobalScope/btoa +--- +
{{APIRef("HTML DOM")}}
+ +

Создает ASCII строку закодированную в base-64 из "строки" бинарных данных.

+ +

Будьте внимательней этот способ не подходит для Unicode строк! Описание работы с Unicode в секции ниже.

+ +

Синтаксис

+ +
var encodedData = window.btoa(stringToEncode);
+ +

Пример

+ +
var encodedData = window.btoa("Hello, world"); // encode a string
+var decodedData = window.atob(encodedData); // decode the string
+
+ +

Замечания

+ +

Вы можете воспользоваться этим способом, чтобы избежать проблем при передаче данных через сетевое соединение. Для этого нужно перекодировать данные в base64 и отправить их, и на другой стороне с помощью метода {{domxref("WindowBase64.atob","window.atob()")}} декодировать полученные данные в исходный вид. Например, вы можете перекодировать управляющие символы ASCII с 0 до 31.

+ +

btoa() также доступна для XPCOM компонентов реализованных в JavaScript, даже если window не является глобальным объектом в компонентах.

+ +

Строки Юникод

+ +

В большинстве браузеров, вызов window.btoa() на Unicode строке выбросит исключение Character Out Of Range (Символ вне допустимого диапазона).

+ +

Чтобы избежать этого, воспользуйтесь патерном, предложеным Johan Sundström:

+ +
function utf8_to_b64(str) {
+    return window.btoa(unescape(encodeURIComponent(str)));
+}
+
+function b64_to_utf8(str) {
+    return decodeURIComponent(escape(window.atob(str)));
+}
+
+// Usage:
+utf8_to_b64('✓ à la mode'); // JTI1dTI3MTMlMjUyMCUyNUUwJTI1MjBsYSUyNTIwbW9kZQ==
+b64_to_utf8('JTI1dTI3MTMlMjUyMCUyNUUwJTI1MjBsYSUyNTIwbW9kZQ=='); // "✓ à la mode"
+
+utf8_to_b64('I \u2661 Unicode!'); // SSUyNTIwJTI1dTI2NjElMjUyMFVuaWNvZGUlMjUyMQ==
+b64_to_utf8('SSUyNTIwJTI1dTI2NjElMjUyMFVuaWNvZGUlMjUyMQ=='); // "I ♡ Unicode!"
+
+
+ +

Более правильный и производительный способ - это конвертировать DOMString в UTF-8 строку передав typed arrays. Как это сделать узнать можно здесь в этом параграфе.

+ +

Спецификации

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#dom-windowbase64-btoa', 'WindowBase64.btoa()')}}{{Spec2('HTML WHATWG')}}No change since the latest snapshot, {{SpecName("HTML5.1")}}.
{{SpecName('HTML5.1', '#dom-windowbase64-btoa', 'WindowBase64.btoa()')}}{{Spec2('HTML5.1')}}Snapshot of {{SpecName("HTML WHATWG")}}. No change.
{{SpecName("HTML5 W3C", "#dom-windowbase64-btoa", "WindowBase64.btoa()")}}{{Spec2('HTML5 W3C')}}Snapshot of {{SpecName("HTML WHATWG")}}. Creation of WindowBase64 (properties where on the target before it).
+ +

Совместимость браузеров

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatVersionUnknown}}{{CompatGeckoDesktop(1)}}[1]10{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatGeckoMobile(1)}}{{CompatNo}}{{CompatUnknown}}{{CompatVersionUnknown}}
+
+ +

[1] btoa() также доступна для XPCOM компонентов реализованных в JavaScript, даже если window не является глобальным объектом в компонентах.

+ +

Смотрите также

+ + diff --git a/files/ru/web/api/windowbase64/index.html b/files/ru/web/api/windowbase64/index.html new file mode 100644 index 0000000000..40051820b4 --- /dev/null +++ b/files/ru/web/api/windowbase64/index.html @@ -0,0 +1,120 @@ +--- +title: WindowBase64 +slug: Web/API/WindowBase64 +tags: + - API + - HTML-DOM + - Helper + - NeedsTranslation + - TopicStub + - WindowBase64 +translation_of: Web/API/WindowOrWorkerGlobalScope +--- +

{{APIRef("HTML DOM")}}

+ +

The WindowBase64 helper contains utility methods to convert data to and from base64, a binary-to-text encoding scheme. For example it is used in data URIs.

+ +

There is no object of this type, though the context object, either the {{domxref("Window")}} for regular browsing scope, or the {{domxref("WorkerGlobalScope")}}  for workers, implements it.

+ +

Properties

+ +

This helper neither defines nor inherits any properties.

+ +

Methods

+ +

This helper does not inherit any methods.

+ +
+
{{domxref("WindowBase64.atob()")}}
+
Decodes a string of data which has been encoded using base-64 encoding.
+
{{domxref("WindowBase64.btoa()")}}
+
Creates a base-64 encoded ASCII string from a string of binary data.
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#windowbase64', 'WindowBase64')}}{{Spec2('HTML WHATWG')}}No change since the latest snapshot, {{SpecName("HTML5.1")}}.
{{SpecName('HTML5.1', '#windowbase64', 'WindowBase64')}}{{Spec2('HTML5.1')}}Snapshot of {{SpecName("HTML WHATWG")}}. No change.
{{SpecName("HTML5 W3C", "#windowbase64", "WindowBase64")}}{{Spec2('HTML5 W3C')}}Snapshot of {{SpecName("HTML WHATWG")}}. Creation of WindowBase64 (properties where on the target before it).
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureFirefox (Gecko)ChromeInternet ExplorerOperaSafari
Basic support{{CompatGeckoDesktop(1)}} [1]{{CompatVersionUnknown}}10.0{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureFirefox Mobile (Gecko)AndroidIE MobileOpera MobileSafari Mobile
Basic support{{CompatGeckoMobile(1)}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

[1]  atob() is also available to XPCOM components implemented in JavaScript, even though {{domxref("Window")}} is not the global object in components.

+ +

See also

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