HTML5 scripting JavaScript API

20.1 Atomics 与 SharedArrayBuffer

Cross-document messaging

Cross-document messaging, sometimes abbreviated as XDM (cross-document messaging), is
the ability to transfer information between different execution contexts (such as different worker threads or pages from different sources). For example, a page on www.wrox.com wants to communicate with a page
on p2p.wrox.com contained in an inline pane . Before XDM, it took a lot of work to implement this communication in a secure manner. XDM
standardizes this function in a safe and easy-to-use way.
Note that cross-context messages are used for communication between windows or between worker threads. This section mainly introduces the use of
postMessage() to communicate with other windows. For communication between worker threads, MessageChannel and
BroadcastChannel, please refer to Chapter 27.
The core of XDM is the postMessage() method. In addition to XDM, this method name has been used in many places in HTML5,
but the purpose is the same, all of which are to transfer data to another location.
The postMessage() method receives 3 parameters: a message, a string representing the target receiving source, and an optional array of transferable objects (only
related to worker threads). The second parameter is very important for security, and it can limit the browser's goal of delivering data. Let’s look at an
example:
let iframeWindow = document.getElementById("myframe").contentWindow;
iframeWindow.postMessage("A secret", "http://www.wrox.com"); The
last line of code tries to inline the window Send a message in the grid, and the source must be "http://www.wrox.com".
If the source matches, then the message will be delivered to the inline pane; otherwise, postMessage() does nothing. This restriction can protect
information from being leaked due to a change of address. If you don't want to limit the receiving destination, you can pass "*" to the second parameter of postMessage(),
but this is not recommended.
After receiving the XDM message, the message event will be triggered on the window object. This event is triggered asynchronously, so
there may be a delay from when the message is sent to when the message is received (the receiving window triggers the message event). The event
object passed to the onmessage event handler contains the following three important information.
 data: The string data passed to postMessage() as the first parameter.
 origin: The source of the document sending the message, for example "http://www.wrox.com".  source: The proxy of the window object in the document sending the message. This proxy object is mainly used
to execute the postMessage() method in the window that sent the previous message . If the sending window has the same source, then this object should be the window
object.
It is very important to verify the source of the sending window after receiving the message.
Just as the second parameter of postMessage() can ensure that data will not be accidentally transmitted to unknown pages, checking the source of the send window in the onmessage event handler can ensure that the data comes from the correct
place. The basic usage is as follows:
window.addEventListener("message", (event) => { // Ensure from the intended sender

if (event.origin == "http://www.wrox.com") { // Do some processing on the data processMessage(event.data); // Optional: send a message to the source window event.source.postMessage ("Received!", "http://p2p.wrox.com"); } }); In most cases, event.source is a proxy for a window object, not an actual window object. Therefore , the information under all windows cannot be accessed through it. It is best to only use postMessage(), this method always exists and can be called. XDM has some weirdness. First of all, the initial implementation of the first parameter of postMessage() is always a string. Later, the first parameter was changed to allow data of any structure to be passed in, but not all browsers have implemented this change. For this, it is best to just send the string via postMessage(). If you need to pass structured data, it is best to call JSON.stringify() on the data first , pass it through postMessage(), and then call JSON.parse() in the onmessage event handler . It is very convenient to use XDM when loading different domains through the embedded pane. This method is very common in mashups and social applications . By using XDM to communicate with the web page in the embedded pane, the security of the containing page can be guaranteed. XDM can also be used to communicate between pages of the same origin.















20.3 Encoding API

The Encoding API is mainly used to implement the conversion between strings and stereotyped arrays. The specification adds 4 new global classes for performing conversions:
TextEncoder, TextEncoderStream, TextDecoder, and TextDecoderStream.
Note that compared to bulk encoding and decoding, support for stream encoding and decoding is very limited.
20.3.1 Text
Encoding The Encoding API provides two methods to convert a string into a regular array binary format: batch encoding and stream encoding. When converting a character
string into a fixed array, the encoder always uses UTF-8.

20.4 File API 与 Blob API

One of the main pain points of web applications is the inability to manipulate files on the user's computer. Before 2000, the only way to process files
was to put them in a form, nothing more. The File API and Blob API are designed to allow web developers to
access files on the client machine in a secure way, so as to better interact with these files.

20.4.1 File type

The File API is still based on the file input field in the form, but adds the ability to directly access file information. HTML5
adds the files collection to the file input element on the DOM. When the user selects one or more files in the file field, the files
collection will contain a group of File objects, representing the selected files. Every File object has some read-only properties.
 name: The file name in the local system.
 size: file size in bytes.
 type: A string containing the MIME type of the file.
 lastModifiedDate: A string representing the last modification time of the file. This attribute is only implemented by Chome.
For example, by monitoring the change event and then traversing the files collection, you can get the information of each selected file:
let filesList = document.getElementById("files-list");
filesList.addEventListener("change", (event) => { let files = event.target.files, i = 0, len = files.length; while (i <len) { const f = files[i]; console.log( ); i++; } });





${f.name} (${f.type}, ${f.size} bytes)


Native drag and drop

Drag and drop event

Media element

Attributes

Attributes type of data Description
autoplay B Get or set autoplay
controls B Get or set the controls property, used to show or hide the controls built into the browser
currentLoop Int The number of times the media file has been looped
currentSrc S The URL of the currently playing media file
currentTime F Seconds elapsed
defaultPlaybackRate F Get or set the default playback speed
duration F Total media playing time
ended B Whether the playback is complete
loop B Get or set whether to start playing from the beginning after the media file is played
muted B Get or set whether to mute

20.7 Notifications API

Use HTML5 Notification to implement desktop notifications
Notifications API is used to display notifications to users. No matter from which point of view, the notification here is very similar to the alert() dialog box:
both use JavaScript API to trigger browser behavior outside the page, and allow the page to handle the user's interaction with the dialog box or notification popup
. However, notifications provide more flexible customization capabilities.
The Notifications API is very useful in Service Workers. Progressive Web Application (PWA, Progressive Web Application)
can display a message to the user when the page is inactive by triggering a notification, which looks like a native application.
20.7.1 Notification permissions The
Notifications API may be abused, so two security measures are enabled by default:
 Notifications can only be triggered in code running in a security context;
 Notifications must be clearly approved by the user in accordance with the principle of each source .
The user authorization to display the notification is done through a dialog box inside the browser. Unless the user does not give a clear answer to allow or deny
, this permission request will only appear once for each domain. The browser will remember the user's choice, and if it is rejected, it cannot be repeated.
The page can use the global object Notification to request notification permissions from the user. This object has a requestPemission()
method, which returns an appointment, which will be resolved after the user performs an operation on the authorization dialog box.
Notification.requestPermission()
.then((permission) => {
console.log('User responded to permission request:', permission);
}); The
"granted" value means that the user has explicitly authorized the permission to display notifications. Values ​​other than this mean that the display notification will fail silently
. If the user refuses authorization, this value is "denied". Once rejected, it cannot be restored programmatically because it is impossible to
trigger the authorization prompt.
20.7.2 Show and hide notifications The
Notification constructor is used to create and display notifications. The simplest form of notification is to display only a title. The
content of this title can be passed to the Notification constructor as the first parameter. Calling Notification in the following way should
display the notification immediately:
new Notification('Title text!');
You can customize the notification through the options parameter, including setting the notification body, picture and vibration, etc.:
new Notification('Title text!', { body:'Body text!', image:'path/to/image.png', vibrate: true });



20.8 Page Visibility API

A common problem in web development is that developers don't know when users are actually using the page. If the page is minimized or hidden
behind other tabs, functions such as polling the server or updating animations may not be necessary. The Page Visibility API is designed to provide
developers with information about whether a page is visible to users.
The API itself is very simple and consists of 3 parts.
 document.visibilityState value, which means one of the following 4 states.
 The page is minimized in the background tab or browser.
 The page is in the foreground tab page.
 The actual page is hidden, but the preview of the page is visible (for example, on Windows 7, when the user moves the mouse over the taskbar icon
, the page preview will be displayed).
 The page is pre-rendered off-screen.
 visibilitychange event, which is triggered when the document changes from hidden to visible (or vice versa).
 document.hidden Boolean value, indicating whether the page is hidden. This may mean that the page is minimized in the background tab or browser
. This value will continue to be supported by browsers for backward compatibility, and document.visibilityState should be used first to
check page visibility.
To be notified when the page changes from visible to hidden or from hidden to visible, you need to listen to the visibilitychange event.
The value of document.visibilityState is one of the following three strings:
 “hidden”
 “visible”
 “prerender”

20.9 Streams API

The Streams API was born to solve a simple but basic problem: how do web applications consume small, ordered
chunks of information instead of large chunks of information? There are two main application scenarios for this capability.
 Large blocks of data may not be available all at once. The response to a network request is a typical example. The network load is
delivered in the form of continuous information packets, and streaming processing allows applications to use the data as soon as it arrives, without having to wait for all the data to be loaded
.
 Large blocks of data may need to be processed in small parts. Video processing, data compression, image encoding, and JSON parsing are
all examples that can be processed in small parts without having to wait until all the data is in memory.
Chapter 24 will introduce the application of Streams API in fetch() when discussing network requests and remote resources, but Streams API
itself is universal. The JavaScript library that implements the Observable interface shares many basic concepts of streams.
Note that although the Fetch API has been supported by all major browsers, the Streams API has not been supported so quickly.
20.9.1 Understanding flow When it comes
to flow, you can think of data as some kind of liquid transported through a pipe. Streaming in JavaScript borrows the concept of pipes
because the principles are the same. According to the specification, “these APIs are actually designed for mapping low-level I/O primitives, including
the normalization of byte streams when appropriate ”. The problem that the Stream API directly solves is to process network requests and read and write disks.
The Stream API defines three streams.
 Readable stream: A stream of data blocks that can be read through a public interface. Data enters the stream internally from the underlying source and is then
processed by the consumer .
 Writable stream: A stream that can write data blocks through a public interface. The producer (producer) writes data into the stream, and the data is internally transferred to the
underlying data slot (sink).
 Conversion stream: It consists of two streams, the writable stream is used to receive data (the writable side), and the readable stream is used to output data (the readable side).
Between these two streams is a transformer, which can check and modify the content of the stream as needed. The basic unit of
chunks, internal queues, and backpressure
flow is chunks. Blocks can be of any data type, but they are usually stereotyped arrays. Each block is a discrete stream segment and
can be processed as a whole. More importantly, the blocks are not of a fixed size and do not necessarily arrive at a fixed interval. In an ideal stream
, the block size is usually approximately the same, and the arrival interval is also approximately the same. However, a good flow implementation requires consideration of boundary conditions.
The various types of flows mentioned earlier have the concept of inlet and outlet. Sometimes, due to different data in and out rates, there may be a
mismatch. For this reason, the flow balance may appear in the following three situations.
 The speed of data processing at the outlet is faster than the data provided by the inlet. The flow outlet is often idle (which may mean that the flow inlet is less efficient
), but only a little memory or computing resources will be wasted, so this kind of flow imbalance is acceptable.
 Inflow and outflow are balanced. This is the ideal state.
 The speed of providing data at the inlet is faster than the speed at which the outlet processes data. This flow imbalance is an inherent problem. There must be
a data backlog somewhere, and the stream must be dealt with accordingly.
Flow imbalance is a common problem, but flow also provides tools to solve this problem. All streams
provide an internal queue for blocks that have entered the stream but have not yet left the stream . For a balanced flow, there will be zero or a small number of queued blocks in this internal queue, because the flow outlet block is dequeued quickly

20.10 Timing API

Page performance is always a topic of concern to Web developers. The Performance interface exposes the
metrics inside the browser through the JavaScript API , allowing developers to directly access this information and implement the functions they want based on this information. This interface is exposed on the
window.performance object. All indicators related to the page, including those that have been defined and those that will be defined in the future, will exist on
this object.
The Performance interface consists of multiple APIs:
 High Resolution Time API
 Performance Timeline API
 Navigation Timing API
 User Timing API
 Resource Timing API
 Paint Timing API

20.12 Web Cryptography API

The Web Cryptography API describes a set of cryptographic tools and regulates how JavaScript implements
encryption in a safe and conventional manner . These tools include generating, using, and applying encryption key pairs, encrypting and decrypting messages, and reliably generating random numbers.
Note that the organization of the encryption interface is a bit strange, the outside is a Crypto object, and the inside is a SubtleCrypto
object. Before the standardization of the Web Cryptography API, the implementation of the window.crypto property in different browsers was
very different. To achieve cross-browser compatibility, standard APIs are exposed on the SubtleCrypto object.

Historical state management

haschange event
knows when the url parameter changes

history.pushState()
state management API, change the url of the browser without loading the page,
parameters: state object, the title of the new state, relative to the url
second parameter can be passed in an empty string
will create a new history The state, which can be "backward", will trigger the popstate event.

The popstate event
has a state attribute, which contains the state object whose first parameter was passed to pushState().
After obtaining the state object, you need to reset the page to the state represented by the data in the state object.

replaceState()
with the new current state does not create a new state in the history state stack, but only overwrites the current state.

history.replaceState({
    
    name:"cc"},"")

Guess you like

Origin blog.csdn.net/cs18335818140/article/details/113826914