Introduction to the
As the front-end ER, our work is inseparable from the Web, and with the growing strength of HTML5, there are also more webapis that come with browsers. This article mainly selects several interesting and useful Webapis to introduce their usage, usefulness and browser support respectively. At the same time, I also made a simple demo for these apis (really simple, style = no ~). These apis are respectively:
- page lifecycle
- onlineState
- Use deviceOrientation to make a cube that rotates with the mobile phone
- battery status
- custom event
- Use execCommand to complete a simple rich text
Page lifecycle
introduce
We can use the document. VisibitilityState to monitor web visibility, whether to unload, but on mobile phones and computers will now this kind of situation, is for instance have been opened for a long time did not open the page, then you see looks can be seen in the browser TAB page content, but need to load point inside. Chrome68 adds freeze and resume events to describe the various life stages of a web page from loading to unloading, including the browser stopping background processes and releasing resources. Moving from one lifecycle phase to another triggers different events, such as onfocus, onBlur, onVisiBilityChange, onFreeze, and so on, to respond to transitions in page state. Specific tutorial recommends everyone to see ruan yifeng god’s tutorial.
usage
window.addEventListener('blur', () = > {})window.addEventListener('visibilitychange', () = > {// Use this method to get the active status of the current TAB page in the browser.
switch(document.visibilityState){
case'prerender': // The page is pre-rendered but the content is not visible
case'hidden': // The content is not visible in the background, minimized, or locked
case'visible': // The content is visible
case'unloaded': // The document is uninstalled}});Copy the code
use
You can watch this demo
Browser support
page visibilituState
Online state
This API is very simple, is to get the current network state, at the same time there are corresponding events to respond to the change of network state.
usage
window.addEventListener('online',onlineHandler)
window.addEventListener('offline',offlineHandler)
Copy the code
use
For example, our website is a video website. When it is playing, the network is interrupted. We can respond to it through this API and give users corresponding prompts and so on.
Browser support
6. Vibration
Make your phone vibrate. Well, it’s that simple.
usage
// You can pass in a number greater than 0, indicating the corresponding length of time to let the phone vibrate, in ms
navigator.vibrate(100)
// You can also pass in an array of numbers, such as: vibrate 300ms, pause 200ms, vibrate 100ms, pause 400ms, vibrate 100ms
navigator.vibrate([300.200.100.400.100])
// You can also pass in zeros or an array of zeros to pause the vibration
navigator.vibrate(0)
Copy the code
use
Used to give the user a hint, such as data verification failure, of course, vibration is more than this, we go to expand it
Browser support
Device Orientation (Gyro)
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
usage
window.addEventListener('deviceorientation',e => {
console.log('Gamma:',e.gamma);
console.log('Beta:',e.beta);
console.log('Alpha:',e.Alpha);
})
Copy the code
use
This is naturally used in web VR scenarios will be relatively more. This is a little demo THAT I wrote
Browser support
battery status
This API is used to get the current battery state
usage
// First check if the current browser supports the API
if ('getBattery' in navigator) {
// Use this method to get the battery object
navigator.getBattery().then(battery= > {
The battery object contains four properties
// Whether the bench is charging
// level Remaining power
// chargingTime Events required to fully charge
// dischargingTime Duration of the current battery
const { charging, level, chargingTime, dischargingTime } = battery;
// At the same time, you can add the change of charging status and power quantity corresponding to the event to the current battery object
battery.onchargingchange = ev= > {
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
use
It is used to remind users of the current power ~~~
Browser support
This browser has very low support…
ExecCommand Executes the command
The execCommand method is exposed when the HTML document is switched to design mode, and can then be used to perform commands such as copy, cut, modify selected text bold, italic, background color, color, indent, insert image, and much more.
usage
Usage is also very simple, here is a brief introduction to a few, detailed introduction you can go to MDN to see. The API takes three arguments, the first is the command to execute, the second argument on MDN is Boolean, which indicates whether to present the user interface, but I haven’t tested the difference, and the third argument is the argument to be passed to use the corresponding command.
// We can insert an iframe and use contentDocument to retrieve and manipulate the HTML document inside the IFrame.
let iframe = document.createElement('ifram');
let doc = iframe.contentDocument;
// Start by switching the HTML document to design mode
doc.designMode = 'on';
// Then you can use execCommand;
// Run the replication command to copy the selected region
doc.execCommand('copy')
// Cut the selected area
doc.execCommand('cut')
/ / all
doc.execCommand('selectAll')
// Make the selected text bold, and the following text will also be bold,
doc.execCommand('bold')
// Italics the selected text, and italics the following text,
doc.execCommand('italic')
// Set the background color. For example, if the background color is red, pass 'red'
doc.execCommand('backColor'.true.'red')
Copy the code
use
I used these commands to write a simple rich text demo. You can take a look at the demo. The result is as follows:
Browser support
CustomEvent (CustomEvent)
We all know how events are bound, but there are times when these events are not enough. A Custom Event can solve this problem.
usage
let dom = document.querySelector('#app');
// Bind the event, and the value passed can be obtained from ev.detail
dom.addEventListener('log-in',(ev) => {
const { detail } = ev;
console.log(detail); // hello
})
// You need to pass in two parameters, one is the event type and the other is an object. The detail is the value passed in
dom.dispatchEvent(new CustomEvent('log-in', {detail:'hello'
}))
Copy the code
use
Bind custom events, which are implemented based on customEvent in the recently popular Omi framework.
Browser support
The last
That’s all. There are more and more Web apis that you won’t know by heart, but this article is just a quick overview. There are many more interesting and important apis, such as: Web Components, Service Worker, Genric Sensor and so on, but there are a lot of people studying these, and relatively many documents. I’m sure you have at least a general idea of how to use these apis, but if you’re interested in understanding how to use them, check out the demo I wrote, or check out the MDN documentation for a deeper look.
reference
- MDN document
- Ruan Yifeng god’s blog
- Web-api-you-dont-know Video Presentation
- www.zhangyunling.com/725.html
- Omi WeElement source