1.Page Visibility
The significance of this new API is that by monitoring the visibility of a web page, it can predict the uninstallation of a web page, and can also be used to save resources and reduce power consumption
When implementing a business requirement, we used onblur and onfocus to determine whether a page was out of focus. With this API, it will be much more convenient.
window.addEventListener('visibilitychange', () => {/*if(document.hidden) {
console.log('Before Tab renders');
}
else {
console.log('Tab is in focus');
}*/
switch(document.visibilityState) {
case 'prerender':
console.log('Before Tab renders');
break;
case 'hidden':
console.log('Tab to hide');
break;
case 'visible':
console.log('Tab is in focus');
break; }});Copy the code
Usage Scenarios:
- Chatroom, which can display message notifications in the browser TAB header (document.title) when not visible;
- Pause audio or video while switching tabs
(2) Lifecycle of a web page
Earlier, I introduced the Page Visibility API. With it, you can listen for web page offloads in various cases.
But it didn’t solve a problem. Android, iOS, and the latest Windows operating systems can automatically stop background processes at any time to release system resources. In other words, web pages can be discarded by the system at any time. The Page Visibility API only fires when a Page is not visible to the user, and does nothing to prevent the Page from being dropped by the system.
To address this, the W3C has created a Page Lifecycle API that will unify the behavior of a web Page from birth to uninstall and define new events that will allow developers to respond to various transitions of web state.
With this API, developers can predict the next state of a web page and do all sorts of specific processing. Chrome 68 supports this API and for older browsers can use the compatible library pagelifecyre.js developed by Google.
Life cycle stage
Example:
window.addEventListener('visibilitychange',() => {// visiBilityChange event is triggered when the visible state of the web page changes, generally occurs in the following scenarios switch(document.visibilityState){// VisibilityChange event is triggered when the visible state of the web page changes.case'prerender': // The page is pre-rendered but the content is not visiblecase'hidden': // The content is not visible in the background, minimized, or lockedcase'visible': // The content is visiblecase'unloaded': // Document uninstalled}})Copy the code
Usage Scenarios:
- Chatroom, which can display message notifications in the browser TAB header (document.title) when not visible;
- Pause audio or video while switching tabs
3.Gamepad
The Gamepad API gives developers a simple, unified way to identify and respond to game controllers (gamepads). It contains three interfaces, two events, and a special function that responds to controller connection and disconnection, obtains other information about the controller, and identifies which key or controller is currently being pressed.
interface
- Gamepad represents a connected game controller.
- A GamepadButton represents a button on a connected gamepad.
- A GamepadEvent represents an event object for controller related events.
Connect to the gamepad
When a new gamepad is connected to a computer, the focus page first receives a GamepadConnected event. If the gamepad is connected when the page loads, the GamepadConnected dispatches events to the focused page when the user presses the button or moves the axis:
window.addEventListener("gamepadconnected".function(e) {console.log(LLDB) {console.log(LLDB) {console.log(LLDB) Console. log(LLDB) // Controller ID Every controller has a unique ID associated with it. Console. log(LLDB) // an array of gamepadButton objects. Console. log(llamepad.axes. Length) // an array of axes that exist on the controller device (e.g. controller sticks)});Copy the code
Disconnect the gamepad
gamepadconnected
) dispatches the second event to the focus window,gamepaddisconnected
:
window.addEventListener("gamepaddisconnected".function(e) {
console.log("Gamepad disconnected from index %d: %s",
e.gamepad.index, e.gamepad.id);
});Copy the code
4.Vibration
The vibrate API allows developers to call the device vibrate directly, using JavaScript, at a given time in vibrate mode
A single vibration
You can oscillate hardware at once by specifying a single value or an array of only one value:
window.navigator.vibrate(200);
window.navigator.vibrate([200]);
Copy the code
Vibration mode
A set of values describes the alternating periods in which the device vibrates and does not vibrate. Each value in the array is converted to an integer and then interpreted alternately as the number of milliseconds the device should vibrate and the number of milliseconds it should not vibrate. Such as:
window.navigator.vibrate([200, 100, 200]);
Copy the code
Stop the vibration
window.navigator.vibrate()
Is 0, blank? Array, or? When array is all "0", can cancel the present? Vibration in progress.
Usage scenario: Vibration can be used to provide sensory feedback when developing Web games or multimedia applications in mobile applications.
5. Device Orientation
The physical orientation of the device can be obtained by binding events, and three values can be obtained, respectively:
- Alpha: the rotation Angle of the device along the Z-axis
- Beta: The rotation Angle of the device along the X axis
- Gamma: Rotation Angle of the device along the Y-axis
Code:
window.addEventListener('deviceorientation',ev => {
console.log('Beta:',ev.beta); // Z-axis rotation Angle console.log('Alpha:',ev.Alpha); // The rotation Angle of the X axis console.log('Gamma:',ev.gamma); // Y axis rotation Angle})Copy the code
6.Clipboard
The Clipboard interface of the Clipboard API provides a way to read and write to the operating system Clipboard.
Copy: Writes text to the clipboard
WriteText () writes text to the clipboard. WriteText () is asynchronous and returns a Promise
navigator.clipboard.writeText('Text to copy')
.then(() => {
console.log('Text has been successfully copied to clipboard');
})
.catch(err => {
// This can happen ifThe user denies Clipboard Permissions: // If the user does not have permission, raise console.error('Cannot copy this text:', err);
});
Copy the code
Paste: Reads text from the clipboard
navigator.clipboard.readText()
.then(text => {
console.log('Pasted content: ', text);
})
.catch(err => {
console.error('Failed to read clipboard contents: ', err);
});
Copy the code
Handling paste Events
There are plans for new events that detect clipboard changes, but for now it’s best to use the “Paste” event. It fits well with the new asynchronous method for reading clipboard text
document.addEventListener('paste', event => {
event.preventDefault();
navigator.clipboard.readText().then(text => {
console.log('Pasted text: ', text);
});
});
Copy the code
7. Document. ExecCommand
Most commands affect document selection (bold, italic, etc.), while other commands insert new elements (add links) or affect entire lines (indent). When using contentEditable, calling execCommand() affects the editable elements currently active. Use this method to perform commands such as copy, cut, modify, background color, color, indent, insert image, select text bold, italic, and so on
let iframe = document.createElement('ifram');
letdoc = iframe.contentDocument; // Switch the HTML document to design modeexecCommand
doc.designMode = 'on'; // Then you can use itexecCommand this Command. ExecCommand execCommand execCommand execCommand execCommand execCommand'selectAll'// Make the selected text bold, and the following text will also be bold, doc. ExecCommand ('bold'// Italicize the selected text, and the following text will also be italicized, doc. ExecCommand ('italic') // Set the background color, for example, set the background color to red'red'Can doc. ExecCommand ('backColor'.true.'red')
doc.execCommand('copy'// Cut the selected area doc.execCommand('cut')
Copy the code
Easy rich text editor
Ambient Light (Ambient Light Sensor)
AmbinentLightSensor()
The constructor creates a newAmbientLightSensor
Object, it returns the photocurrent level or illuminance of the ambient light around the host device.
use
let sensor = new AmbientLightSensor();
sensor.start();
sensor.onchange = (e) => {
console.log(e.reading.illuminance);
};
sensor.stop();
Copy the code
Battery status.
Allows web pages to access battery information from desktop and mobile devices.
// First check if the current browser supports the APIif ('getBattery' inThen (battery => {// The battery object contains four attributes. // Whether a charging point is charging // Level / / soc chargingTime charged the event / / dischargingTime current battery can use time const {chargingTime charging, level, dischargingTime } = battery; Battery. onChargingchange => {const {currentTarget} = ev; const { charging } = currentTarget; }; battery.onlevelchange = ev => { const { currentTarget } = ev; const { level } = ev; }})}else {
alert('Current browser does not support ~~~')}Copy the code
10. Online state
Determine whether the web page is connected to the Internet.
console.log(navigator.onLine ? 'online' : 'offline');
window.addEventListener('offline', networkStatus);
window.addEventListener('online', networkStatus);
function networkStatus(e) {
console.log(e.type);
}Copy the code
11, Web VR
The WebVR API provides support for rendering virtual reality devices — such as headsets like Oculus Rift or HTC Vive that connect to Web apps. It allows developers to convert location and movement information into movement in a 3D scene. There are many interesting applications for this technology, such as virtual product demonstrations, interactive training courses, and super-immersive first-person games
For more information, please visit MDN
reference
Ruan yifeng Page Visibility API tutorial
MDN document
JS vibrate is an API that makes your phone vibrate