当前位置:网站首页>10 Web APIs
10 Web APIs
2022-07-27 00:46:00 【Bug I'll write it】
10 A little-known but useful Web API
Lesser Known but Useful Web APIs
List of articles
Fullscreen
Display the specified elements in full screen
<div className="wrapper">
<div id="fs_id">
<img src="path/to/santa.jpg" alt="santa" />
</div>
<button onclick="manageFullscreen()">
Enter Fullscreen with Santa
</button>
</div>
function manageFullscreen () {
document.getElementById('fs_id').requestFullscreen();
}
Check whether the browser supports
if (document.fullscreenEnabled) {
// supported
} else {
// not supported
}
Monitoring events
onfullscreenchange: Full screen change eventonfullscreenerror: Full screen failure event
Clipboard
Check for support
if (navigator.clipboard && navigator.clipboard.read && navigator.clipboard.write) {
// supported
} else {
// not supported
}
Write the contents to the clipboard
async function performCopy(event) {
event.preventDefault();
try {
await navigator.clipboard.writeText(copyText);
console.log(`${
copyText} copied to clipboard`);
} catch (err) {
console.error('Failed to copy: ', err);
}
}
// This method does not require user permission , But it's better to put it in try...catch There's no mistake in it .
Read content from clipboard and process it
async function performPaste(event) {
event.preventDefault();
try {
const text = await navigator.clipboard.readText();
document.querySelector('#output').value = text;
console.log('Pasted content: ', text);
} catch (err) {
console.error('Failed to read clipboard contents: ', err);
}
// After the user clicks on the page , Will output the text in the clipboard . Be careful , The browser will pop up a dialog box , Ask the user if they agree to the script reading the clipboard .
// If the user disagrees , The script will report an error . At this time , have access to try...catch structure , Deal with errors .
}
Because users may put sensitive data ( Like passwords ) Put it on the clipboard , Allowing scripts to read arbitrarily is a security risk , So this API There are a lot of security restrictions .
First ,Chrome Browser rules , Only HTTPS Protocol pages can only use this API. however , development environment (localhost) Allow the use of non encrypted protocols .
secondly , The user's permission needs to be explicitly obtained when calling . The specific implementation of permissions uses Permissions API, There are two permissions associated with the clipboard :clipboard-write( Write permissions ) and clipboard-read( Read permission )." Write permissions " Automatically grant scripts , and " Read permission " Must be given with the express consent of the user . in other words , Write to the clipboard , Scripts can be done automatically , But when you read the clipboard , The browser will pop up a dialog box , Ask the user if they agree to read .
in addition , It should be noted that , The script always reads the current page's clipboard . One of the problems with this is , If you paste the relevant code into the developer tool and run it directly , There may be a mistake , Because the current page at this time is the window of the developer tool , Not a web page .
Resize Observer
window.onresize Events are usually wasteful , Because it will monitor the size change of each element ( Only window The object has resize event ), Rather than specific changes to an element . If we only want to monitor the change of an element , This operation is a waste of performance .
ResizeObserver API Can help us : Listen to a DOM Changes in nodes , Such changes include but are not limited to :
- The appearance and hiding of a node
- The size of a node changes
const myObserver = new ResizeObserver(entries => {
entries.forEach(entry => {
console.log(' Size position ', entry.contentRect)
console.log(' Monitoring DOM', entry.target)
});
});
// monitor DOM Elements One ResizeObserver Object can listen to multiple DOM node
myObserver.observe(document.body);
myObserver.observe(document.querySelector('#app'));
// Cancel monitoring
window.setTimeout(() => {
myObserver.unobserve(document.body); // You need to receive a parameter
}, 2000)
// Cancel all listening
window.setTimeout(() => {
myObserver.disconnect() // You won't listen anymore document.body, and #app The node
}, 4000)
- ResizeObserverEntry
- target Monitored DOM object
- contentRect
- width: Refers to the width of the element itself , It doesn't contain padding,border value
- height: Refers to the height of the element itself , It doesn't contain padding,border value
- top: finger padidng-top Value
- left: finger padding-left Value
- right: finger left + width Value
- bottom: value top + height Value
- x: Size and top identical ,y: Size and left identical
Image Capture
ImageCapture The interface provides a method to capture images or frames from cameras or other photographic devices . It provides an interface , Used to pass from valid .MediaStreamTrack
var imageCapture;
function onGetUserMediaButtonClick() {
navigator.mediaDevices.getUserMedia({
video: true})
.then(mediaStream => {
document.querySelector('video').srcObject = mediaStream;
const track = mediaStream.getVideoTracks()[0];
imageCapture = new ImageCapture(track);
})
.catch(error => console.log(error));
}
function onGrabFrameButtonClick() {
imageCapture.grabFrame()
.then(imageBitmap => {
const canvas = document.querySelector('#grabFrameCanvas');
drawCanvas(canvas, imageBitmap);
})
.catch(error => console.log(error));
}
function onTakePhotoButtonClick() {
imageCapture.takePhoto()
.then(blob => createImageBitmap(blob))
.then(imageBitmap => {
const canvas = document.querySelector('#takePhotoCanvas');
drawCanvas(canvas, imageBitmap);
})
.catch(error => console.log(error));
}
/* Utils */
function drawCanvas(canvas, img) {
canvas.width = getComputedStyle(canvas).width.split('px')[0];
canvas.height = getComputedStyle(canvas).height.split('px')[0];
let ratio = Math.min(canvas.width / img.width, canvas.height / img.height);
let x = (canvas.width - img.width * ratio) / 2;
let y = (canvas.height - img.height * ratio) / 2;
canvas.getContext('2d').clearRect(0, 0, canvas.width, canvas.height);
canvas.getContext('2d').drawImage(img, 0, 0, img.width, img.height, x, y, img.width * ratio, img.height * ratio);
}
document.querySelector('video').addEventListener('play', function() {
document.querySelector('#grabFrameButton').disabled = false;
document.querySelector('#takePhotoButton').disabled = false;
});
Broadcast Channel
Broadcast Channel API Allow browser context ( window 、 tab 、iframes) and From the same source Communication between working groups .
// send out
const CHANNEL_NAME = "greenroots_channel";
const bc = new BroadcastChannel(CHANNEL_NAME);
const message = 'I am wonderful!';
const sendMessage = () => {
bc.postMessage(message);
}
// receive
const CHANNEL_NAME = "greenroots_channel";
const bc = new BroadcastChannel(CHANNEL_NAME);
bc.addEventListener('message', function(event) {
console.log(`Received message, "${
event.data}", on the channel, "${
CHANNEL_NAME}"`);
const output = document.getElementById('msg');
output.innerText = event.data;
});
performance
Performance It's front-end performance monitoring API.performance Contains three objects , Respectively memory、navigation、timing . among memory It's about memory ,navigation It means source related , That is to say, I jumped from that place .timing It's the critical time .
const performance = window.performance || window.msPerformance || window.webkitPerformance;
if(performance) {
console.log(performance);
}
performance.memory The meaning is to show the memory usage at the moment
- jsHeapSizeLimit The meaning of this attribute is : Memory size limit .
- totalJSHeapSize Express Total memory size .
- usedJSHeapSize Indicates the amount of memory available .
If usedJSHeapSize Greater than totalJSHeapSize Words , Then there will be a memory leak problem , Therefore, it is not allowed to exceed this value .
performance.navigation Meaning is the source information of the page , The object has 2 Attribute values , Namely :redirectCount and type.
- redirectCount: The value means : If there is a redirect , The page comes through several redirects , The default is 0;
- type: The meaning of this value indicates how the page is opened . The default is 0. It can be taken as 0、1、2、255.
- 0(TYPE_NAVIGATE): Indicates normal access to the page ( Non refresh 、 No redirection ).
- 1(TYPE_RELOAD): Said by window.location.reload Refresh the page . If I refresh the next page now , If you look at the value, it becomes 1 了 .
- 2(TYPE_BACK_FORWARD ): Represents progress through the browser 、 Back button to enter the page . If I advance to the next page at this time , Back to the page , Check the printed value , Discovery becomes 2 了 .
- 255(TYPE_RESERVED): It means not entering the page in the above way .
performance.onresourcetimingbufferfull In a callback function . The callback function will execute when the browser's resource time performance buffer is full .
performance.timeOrigin It's a series of time points , To the nearest millisecond . The value in the screenshot above is :1559526951495.139, This value is a dynamic , Refresh , This value will change .
performance.timing It's a series of key points in time , It contains the Internet 、 Analysis and so on a series of time data .

In the order shown above , Let's take a look at the meanings of each field as follows :
navigationStartIt means the timestamp at the end of unloading a page on the same browser . If there is no previous page , Then the value will go with fetchStart The value of is the same .redirectStartThe meaning of this value is the first http Timestamp at the beginning of redirection , If there is no redirection , Or redirect to a different source , Then the value is returned as 0.redirectEndthe last one HTTP Timestamp when redirection is complete . If there is no redirection , Or redirect to a different source , The value is also returned as 0.fetchStartThe browser is ready to use http The time when the document was requested ( Before checking the local cache ).domainLookupStartDNS Domain name query start time , If local caching is used , or Persistent links , This value is related to fetchStart Same value .domainLookupEndDNS Time of domain name query completion , If local caching is used , or Persistent links , This value is related to fetchStart Same value .connectStartHTTP Time to start connection , If it's a persistent link , The value is the same as fetchStart Same value , If an error occurs at the transport layer and a connection needs to be reestablished , So here is the start time of the new link .secureConnectionStartHTTPS Connection start time , If it's not a secure connection , Then the value is 0connectEndHTTP Time to complete connection ( Complete the handshake ). If it's a persistent link , The value is the same as fetchStart Same value , If an error occurs at the transport layer and a connection needs to be reestablished , So here is the new link completion time .requestStarthttp The time when the request to read the real document started , Including reading cache from local , When link error reconnects .responseStartTime to start receiving response ( When we get the first byte ). Including reading cache from local .responseEndHTTP Time when the response is all received ( Get the last byte ). Including reading cache from local .unloadEventStartPrevious page ( Same domain as current page )unload The timestamp , If there is no previous page or the previous page is a different domain , So the value is 0.unloadEventEndand unloadEventStart Corresponding , Back to the previous page unload Time stamp of the completion of the callback function of event binding .domLoadingStart parsing rendering DOM Tree time .domInteractiveFinish parsing DOM Tree time ( It's just DOM Tree parsing complete , But it didn't start loading the web resources ).domContentLoadedEventStartDOM After parsing , Start time of loading resources in the web page .domContentLoadedEventEndDOM After parsing , The time when the resources in the web page are loaded .domCompleteDOM Tree parsing complete , And when the resources are ready .Document.readyState Turn into complete, And will throw readystatechange Related events .loadEventStartload Event sent to document . That is to say load When the callback function starts executing , If there is no binding load event , The value is 0.loadEventEndload The time when the callback function of the event finished executing , If there is no binding load event , The value is 0.
Above is the meaning of each value , Let's have a brief look at , Just get to know , Don't worry too much . Use these values to calculate the white screen time 、 First screen time 、 User operable time nodes , The total download time of the page 、DNS The time of the query 、TCP Link time before , Let's first look at how the traditional scheme is done ?
Battery Status
It provides information about the charging level of the system and provides events to remind the user through the change of battery level or charging state . This can adjust the resource usage status of the application when the power of the device is low , Or save the changes in the application before the battery runs out to prevent data loss .
navigator.getBattery().then((battery) => {
console.log(battery);
// handle the charging change event
battery.addEventListener("chargingchange", () => {
console.log("Battery charging? " + (battery.charging ? "Yes" : "No"));
});
// handle charge level change
battery.addEventListener("levelchange", () => {
console.log("Battery level: " + battery.level * 100 + "%");
});
// handle charging time change
battery.addEventListener("chargingtimechange", () => {
console.log( "Battery charging time: " + battery.chargingTime + " seconds");
});
// handle discharging time change
battery.addEventListener("dischargingtimechange", () => {
console.log("Battery discharging time: " + battery.dischargingTime + " seconds");
});
});
Network Information
Provide relevant Network Information API Network type ( for example ,“wifi”、“ cellular ” etc. )、 Save data mode 、 Bandwidth and other information .
console.log(navigator.connection);
// NetworkInformation
// downlink: 10
// effectiveType: "4g"
// onchange: null
// rtt: 50
// saveData: false
NetworkInformation.downlink read-only
Returns the estimated effective bandwidth in megabits per second , Round to the nearest second 25 Multiple of kilobits .NetworkInformation.downlinkMax read-only
Returns the maximum downlink speed of the underlying connection technology , In megabits per second (Mbps) In units of .NetworkInformation.effectiveType read-only
Returns the valid type of the connection , Express “slow-2g”、“2g”、“3g” or “4g” One of . This value is determined using the group of recently observed round trip time and downlink values .NetworkInformation.rtt read-only
Returns the estimated effective round trip time of the current connection , Round to the nearest 25 Multiples of milliseconds .NetworkInformation.saveData read-only
If the user sets the option of reducing data usage on the user agent , Then return totrue.NetworkInformation.type read-only
Returns the connection type used by the device to communicate with the network . It will be one of the following values :- bluetooth
- cellular
- ethernet
- none
- wifi
- wimax
- other
- unknown
NetworkInformation.onchange event
When the connection information changes and change Events triggered when triggered on this object .
Navigator.vibrate
Navigator.vibrate() Method to make the equipment ( Vibration hardware ) Produce vibration with frequency . If the device does not support vibration , This method will not work . If a vibration mode is already in progress ( When the method is called ), Then the previous vibration mode stops , New ones take their place .
If the method cannot make the equipment vibrate because of providing invalid parameters , It will return false, Otherwise return to true. If the vibration scheme causes long-term vibration , It will be truncated : The maximum vibration duration depends on the specific implementation of each browser .
var successBool = window.navigator.vibrate(pattern);
- pattern
Provide a vibration 、 Pause interval mode . Each value represents the number of milliseconds of alternating vibration or pause . You can provide a single value ( The number of milliseconds of vibration ) Or an array containing integers to vibrate alternately 、 Pause 、 shock .
window.navigator.vibrate(200); // vibrate for 200ms
window.navigator.vibrate([100,30,100,30,100,200,200,30,200,30,200,200,100,30,100,30,100]); // Vibrate 'SOS' in Morse.
BlueTooth
this Web API Allows you to connect to Bluetooth devices .
navigator.bluetooth.requestDevice({
acceptAllDevices: true
}).then(device => {
setDeviceName(device.name);
setDeviceId(device.id)
setDeviceConnected(device.connected);
}).catch(err => {
console.log(err);
setError(true);
})
grammar
Bluetooth.requestDevice(options).then(function(bluetoothDevice) {
... })
- options
The object that sets the device request options . The available options are :- filters[]: One BluetoothScanFilters Array . This filter consists of a BluetoothServiceUUID Array , A name parameter and a namePrefix Parameter composition .
- optionalServices[]: One BluetoothServiceUUID Array .
- acceptAllDevices: boolean Indicates that the request script can accept all Bluetooth devices . The default value is false.
边栏推荐
- Leetcode 301 week
- 用New,delete和用malloc,free申请,释放堆区空间
- [HarekazeCTF2019]encode_and_encode
- 6_梯度下降法(Gradient Descent)
- [NPUCTF2020]ezinclude
- Promise基本用法 20211130
- C language is more than a variety of descriptions of size. Don't stick to one way of writing
- [acwing game 61]
- [qt] meta object system
- [WUSTCTF2020]CV Maker
猜你喜欢
![[PCB open source sharing] stc32g12k128/stc8h8k64u development board](/img/f1/48b344722820ab262e751aebf65411.png)
[PCB open source sharing] stc32g12k128/stc8h8k64u development board

裁剪tif影像
![[红明谷CTF 2021]write_shell](/img/f5/c3a771ab7b40311e37a056defcbd78.png)
[红明谷CTF 2021]write_shell

Matlab simulation of image reconstruction using filtered back projection method

Search engine realizes keyword highlighting

JSCORE day_05(7.6)

Dynamic binding, static binding, and polymorphism

DOM day_02(7.8)网页制作流程、图片src属性、轮播图、自定义属性、标签栏、输入框事件、勾选操作、访问器语法

DOM day_ 02 (7.8) web page production process, picture SRC attribute, carousel chart, custom attribute, tab bar, input box event, check operation, accessor syntax

8_ Polynomial regression and model generalization
随机推荐
[3. Basic search and first knowledge of graph theory]
Operator overloading
Blue Bridge Cup 1004 [recursive] cow story
MySQL common functions (summary)
DOM day_04(7.12)BOM、打开新页面(延迟打开)、地址栏操作、浏览器信息读取、历史操作
Shufflenet series (2): explanation of shufflenet V2 theory
Medical data of more than 4000 people has been exposed for 16 years
Torch. correlation function
Programmers must do 50 questions
[watevrCTF-2019]Cookie Store
[interview: concurrent Article 16: multithreading: detailed explanation of wait/notify] principle and wrong usage (false wake-up, etc.)
[4.10 detailed explanation of game theory]
Drawing warehouse-2 (function image)
JSCORE day_05(7.6)
2020-12-20 99 multiplication table
DOM day_ 04 (7.12) BOM, open new page (delayed opening), address bar operation, browser information reading, historical operation
[2. TMUX operation]
My first blog - confused junior
程序员必做50题
[WUSTCTF2020]CV Maker