Canvas has a very common method canvas.todataURL (), which will convert canvas into the format of data URL. Typically, this data URL is of type image. Consider the following example:
<canvas id="canvas" height="2" width="2"></canvas>
var canvas = document.getElementById('canvas');
var dataURL = canvas.toDataURL();
console.log(dataURL);
/* * data:image/png; base64,iVBORw0KGgoAAAANSUhEUgAAAAIAAAACCAYAAABytg0kAAAADklEQVQYV2NkgAJGGAMAAC0AA03DhRMAAAAASUVORK5CYII= */
Copy the code
Data :[MIME type]; What exactly is a data URL that starts with Base64?
- First data URL
- What’s the difference between a data URL and a traditional URL?
- What does the data URL look like when entered in the browser address bar?
- Data URL syntax
- What are the four parts of a data URL?
[<mediatype>]
details[;base64]
and<data>
details- Common data URL form
- String Base64 encoding and decoding language implementation
- Why base64 in the data URL?
- Unix, javascript, Node, Python, PHP, Java,.NET base64 encoding
- Data URL FAQ
First data URL
- A data URL is a specially formatted URL that is prefixed with
data:
- The Data URL allows content creators to embed small files in Documents
- Used to be called Data URIs until WHATWG changed its name to Data URL(s)
What’s the difference between a data URL and a traditional URL?
Modern browsers treat data urls as the only opaque source, not the one responsible for navigation. How to understand this sentence? Look at this example:
// data URLdata:image/png; base64,iVBORw0KGgoAAAANSUhEUgAAAAIAAAACCAYAAABytg0kAAAADklEQVQYV2NkgAJGGAMAAC0AA03DhRMAAAAASUVORK5CYII=// Traditional URL
https://www.google.com
Copy the code
As can be seen from the above results, data URLS are different from traditional urls. The traditional URL is entered in the address bar of the browser and can be directly navigated to the target address. Data URL is a URL representation of data, which can be understood as representing data with URL. Usually, the data refers to images.
What does the data URL look like when entered in the browser address bar?
Normally, you can see the image represented by this URL.
<! DOCTYPE html><html lang="en">
<body>
<canvas id="canvas"></canvas>
</body>
<script>
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
ctx.font = "48px serif";
ctx.fillText("Hello Canvassssssssss".0.75 + 24);
var dataURL = canvas.toDataURL();
console.log(dataURL);
</script>
</html>
Copy the code
Data URL syntax
What are the four parts of a data URL?
data:[<mediatype>][;base64],<data>
Copy the code
composition | meaning |
---|---|
data: |
The prefix |
[<mediatype>] |
MIME typeRepresents the type of data |
[;base64] |
Optional Base64 identifier |
<data> |
The data itself |
[<mediatype>]
details
- Mediatype is a string of MIME type, such as ‘image/ JPEG ‘.
- If ignored, the default is “text/plain; Charset = US – the ASCII “.
- Canvas.todataurl () is not ignored and the default MIMIE type is “image/ PNG “.
[;base64]
and<data>
details
- If data is plain text, you can simply embed the text (using the appropriate entity or escape depending on the document type).
- If data is not plain text, it can be identified as Base64 and embedded with base64-encoded binary data.
Common data URL form
- Simple text/plain data
- Plain Text/Palin data in Base64 form
- HTML fragments: Common tags
- HTML fragments: Script tags that execute JS
Simple text/plain data
Hello World!
data:,Hello%2C%20World! // MIME typeAnd; There is no base64, only ':' between data and dataCopy the code
Note the percent-encoding (url-encoding) of quotes and Spaces. For CSV data (” text/ CSV “), percent-encoding needs to preserve the end of the line separating the spreadsheet rows.
Plain Text/Palin data in Base64 form
Hello World!
data:text/plain; base64,SGVsbG8sIFdvcmxkIQ==Copy the code
HTML fragments: Common tags
<h1>Hello, World! </h1>
data:text/html,%3Ch1%3EHello%2C%20World! %3C%2Fh1%3ECopy the code
HTML fragments: Script tags that execute JS
<script>alert('hi'); </script>
data:text/html,<script>alert('hi');</script>
Copy the code
Execute the js script tag. Note that closing the script tag is required.
String Base64 encoding and decoding language implementation
Why base64 in the data URL<data>
?
- A base64 string represents binary data in base64, which is an ASCII string.
- Base64 strings are URL-safe because they are composed only of ASCII characters, so base64 is applied to of the data URL.
Unix, javascript, Node, Python, PHP, Java,.NET base64 encoding
"[email protected]"
"Zm9vQGdtYWlsLmNvbQ=="
Copy the code
1.unix (author: Peng Zhao)
Decoding: echo “Zm9vQGdtYWlsLmNvbQ = =” | base64 – D code: echo “[email protected]” | base64
2.javascript (author: Kai Gao)
var encodedData = window.btoa("[email protected]"); / / code
var decodedData = window.atob("Zm9vQGdtYWlsLmNvbQ=="); / / decoding
console.log(encodedData,decodedData)
Copy the code
3.nodejs (author: Kai Gao)
/ / base64 encoding
var b = new Buffer("[email protected]");
var s = b.toString('base64')
console.log("Email address :"+s)
/ / base64 decoding
var b = new Buffer("Zm9vQGdtYWlsLmNvbQ=="."base64")
var s = b.toString();
console.log("Mailbox decoding :"+s)
Copy the code
4.python (author: Peng Zhao)
import base64
base64.b64encode("[email protected]")
base64.b64decode("Zm9vQGdtYWlsLmNvbQ==")
Copy the code
5.php (author: Chuang Shen)
$a = '[email protected]';
$b = base64_encode($a);/ / code
echo $b;
$c = base64_decode($b);/ / decoding
echo $c;
? >
Copy the code
6.java (author: Chuang Shen)
String str = "[email protected]";
String encodeStr = new String(Base64.encode(str.getBytes()));
System.out.println(encodeStr);
String decodeStr = Base64.base64Decode(encodeStr);
System.out.println(decodeStr);
Copy the code
7.. net (author: Peng Li)
Static void Main(string[] args) {console. WriteLine(" input :"); var str = Console.ReadLine(); Byte [] EncryptionByte = encoy.utf8.getBytes (STR); // Encrypt byte[] EncryptionByte = encoy.utf8.getBytes (STR); var EncryptionStr = Convert.ToBase64String(EncryptionByte); Console.WriteLine(" Result: "+ EncryptionStr); Byte [] DecryptionByte = convert.frombase64string (EncryptionStr); // DecryptionByte [] DecryptionByte = convert.frombase64string (EncryptionStr); var DecryptionStr = Encoding.UTF8.GetString(DecryptionByte); Console.WriteLine(" decryption result: "+ DecryptionStr); }Copy the code
View the string Base64 encoding and decoding of multiple languages to make clear the context of base64 multi-language implementation.
Data URL FAQ
Lists some common problems with creating and using data urls.
data:text/html,lots of text... <p><a name%3D"bottom">bottom</a>? arg=valCopy the code
What it actually stands for is:
lots of text... <p><a name="bottom">bottom</a>? arg=valCopy the code
- grammar
- Formatting in HTML
- Length limit
- Absence of exception handling
- String query is not supported
- Security issues
grammar
The format of the data URL is very simple, and it’s easy to forget to put a comma before data, or to incorrectly encode the data in Base64 format.
Formatting in HTML
The data URL provides a file in a file that can be very wide relative to the closed document. As a URL, data should be formatted with white space (newline, TAB, or space), but there are some problems with base64 encoding.
Length limit
Although Firefox supports live data URL lengths, browsers do not need to support any maximum specific length of data. For example, Opera 11 limits the URL length to 65535 and the data URL to 65529 (65529 is the base64 encoded length).
Data URL length limit of mainstream browsers
- Chrome – 2MB for the current document. Otherwise the limit is the in-memory storage limit for – arbitrary blobs: if x64 and NOT ChromeOS or Android, then 2GB; otherwise, total_physical_memory / 5 (source).
- Firefox – unlimited
- IE ≥ 9 & Edge – 4GB
Quoted in: Data protocol URL size limitations
Absence of exception handling
Invalid media arguments, or ‘base64’ typesetting errors, are ignored, but no errors are reported.
String query is not supported
The data portion of the data URL is opaque, so if you use a Query String (such as < URL >? Parameter-data) will contain only the URL query string in the data. This means that the query is invalid and treated as part of the data.
Security issues
Many security issues, such as phishing, are related to data urls and navigate to them at the top level of the browser. To address these issues, in Firefox 59+ (release, starting with 58), the top-level navigation of data data:// urls has been banned.
References:
- Developer.mozilla.org/en-US/docs/…
- Developer.mozilla.org/en-US/docs/…