| <!DOCTYPE html> | |
| <head> | |
| <title>Text Encoding Workaround</title> | |
| <style> | |
| div { | |
| background-color: rgb(200, 200, 200); | |
| height: 50px; | |
| } | |
| </style> | |
| </head> | |
| <body> | |
| <div id="text-decoded"> </div> | |
| <div id="text-encoded"> </div> | |
| <div id="large-string-encode"> </div> | |
| <div id="large-string-decode"> </div> | |
| <script> | |
| /* | |
| Text encoding is not natively supported by Cobalt. | |
| There is work in progress to support it in Cobalt 22.lts. | |
| In the mean time, a workaround is presented here, that could be | |
| used to encode/decode to/from UTF-8. | |
| The full IDL definition can be found at: | |
| https://cobalt.googlesource.com/cobalt/+/refs/heads/21.lts.1+/src/cobalt/fetch/fetch_internal.idl, | |
| ant it is available in 19.lts.1+ versions. | |
| **WARNING:** As mentioned in the IDL file, the utility was not | |
| meant to be public and should not be used outside of the fetch | |
| implementation. | |
| **WARNING:** Even when this is a native implementation it might still | |
| not be ideal to handle very large strings due to its performance. | |
| **WARNING:** DecodeFromUTF8 throws a simple TypeError exception | |
| when the data provided is not a valid utf-8. | |
| */ | |
| // Using FetchInternal.decodeFromUTF8 | |
| var arr = new Uint8Array( | |
| [ 228, 189, 160, 229, 165, 189, 239, 188, 140, 228, | |
| 184, 150, 231, 149, 140, 33, 32, 208, 159, 209, | |
| 128, 208, 184, 208, 178, 208, 181, 209, 130, 32, | |
| 208, 188, 208, 184, 209, 128, 33, 32, 72, 101, | |
| 108, 108, 111, 32, 119, 111, 114, 108, 100, 33]); | |
| var utf8_string = FetchInternal.decodeFromUTF8(arr); | |
| document.getElementById("text-decoded").innerHTML = utf8_string; | |
| // Using FetchInternal.encodeToUTF8 | |
| var str = "你好,世界! Привет мир! Hello world!"; | |
| var u8_arr = FetchInternal.encodeToUTF8(str); | |
| document.getElementById("text-encoded").innerHTML = u8_arr.toString(); | |
| // Trying very large strings; | |
| // Note: This section takes a while for this to be completed. | |
| var kSize = 1048576; // 8 x 1024 x 128 | |
| var char = "c"; | |
| var large_str = char.repeat(kSize); | |
| var u8_large_arr = FetchInternal.encodeToUTF8(large_str); | |
| document.getElementById("large-string-encode").innerHTML = u8_large_arr.toString(); | |
| var large_decoded_str = FetchInternal.decodeFromUTF8(u8_large_arr); | |
| document.getElementById("large-string-decode").innerHTML = large_decoded_str; | |
| </script> | |
| </body> | |
| </html> |