Foreword
The reason for writing this article is that I recently made a shared screen online presentation ppt demand and discovered a new world of navigator. It turns out that it is so simple to enable screen sharing on the web. Before contacting it, I thought it was such a high-level function, and I was a little flustered when I reviewed the requirements.
People are always afraid of what they don’t understand
Because before this, although I know that navigator records some user agent information, the common use is to use Navigator.userAgent
to judge the current browser environment (many front-ends are How about it~ hahaha, if you are too, deduct 1 in the comment area, if you have a deep understanding, button the eyeball in the comment area). Little is known about its other APIs. Because in my opinion, it is only used to record information, but it has many powerful APIs, such as turning on the camera and keeping the screen always on.
So I read through the documentation on navigator on mdn, and recorded some APIs that may be used in the future to see what you know. If there are any mistakes, please correct them in the comment area!
This article only records some attributes of the navigator, and its method will be recorded in the next article, welcome to pay attention!
1. clipboard
The clipboard property returns a
Clipboard
object that can read and write the contents of the clipboard.
This object instance has four methods: read, readText, write, writeText.Purpose: Realize the functions of cutting, copying and pasting on the web.
Compatibility: Not bad, use it boldly!
//clipboard instance const theClipboard = navigator. clipboard;
read()
Reads data (such as pictures) from the clipboard and returns aPromise
object. After the data is retrieved, the promise returns an array ofClipboardItem
objects to provide clipboard data. can be text data or binary data (such as pictures). This method requires the user to explicitly give License;readText()
Reads text from the operating system; returns aPromise
that is returned to the clipboard after the text has been retrieved from the clipboard the text data inside;write()
is used to write arbitrary data to the clipboard, which can be text data or binary data, which is an asynchronous operation;writeText()
is used to write text content to the clipboard.
//read async function getClipboardContents() {<!-- --> try {<!-- --> const clipboardItems = await navigator. clipboard. read(); for (const clipboardItem of clipboardItems) {<!-- --> for (const type of clipboardItem. types) {<!-- --> const blob = await clipboardItem. getType(type); // we can now use blob here } } } catch (err) {<!-- --> console.error(err.name, err.message); } } //readText async function getClipboardText(){<!-- --> const text = await navigator. clipboard. readText(); console. log(text); } //write async function copyImage() {<!-- --> const input = document. getElementById("file"); const blob = new Blob(["sample 2"], {<!-- --> type: "text/plain" }); const clipboardItem = new ClipboardItem({<!-- --> "text/rt": blob, "image/png": input.files[0], }); const response = await navigator. clipboard. write([clipboardItem]); console. log(response); } //writeText async function writeDataToClipboard() {<!-- --> const result = await navigator.clipboard.writeText("Hello"); console. log(result); }
2. connection (network connection status)
Navigator.connection
is used to obtain the network connection information of the device.
The information that can be obtained is: downlink (network downlink speed), effectiveType (network type), onchange (value represents network status change) rtt (estimated round-trip time) saveData (open/request data protection mode) strong>.Purpose: To switch content clarity based on the user’s network status.
Compatibility: Use with caution! The functions in the experiment, such as safari, Firefox, and IE are not supported at all, and chrome currently only supports the three attributes of downlink, effectiveType, and rtt
//network status instance const connectionInfo = navigator. connection
3. geolocation
Navigator.geolocation
The read-only property returns aGeolocation
object, using the methods of this object to obtain the geographic location of the device.Note: 1. The location permission of the client that opens the webpage must be granted;
2. The HTTPS protocol must be used
Compatibility: All major browsers support, including ie
navigator.geolocation.getCurrentPosition( function(position) {<!-- --> console.log(position.coords.latitude, position.coords.longitude); }, function(error){<!-- --> console. error(error. message); }, {<!-- --> enableHighAccuracy: true ,timeout: 5000 } );
Example:
4. mediaDevices (media capture and streaming)
The
Navigator.mediaDevices
property returns aMediaDevices
object, and theMediaDevices
interface provides Access to media input devices such as cameras and microphones, and screen sharing. Essentially, it gives you access to any hardware source of media data.
This object provides access to connected media input devices such as cameras and microphones, as well as screen sharing. This object provides 5 APIs:enumerateDevices(), getDisplayMedia(), getSupportedConstraints(), getUserMedia(), selectAudioOutput()
Purpose: Web-side screen sharing, used for webRTC for real-time audio and video, such as remote collaboration, online conference presentation files, online classrooms, etc.
Compatibility: It is also not supported by spicy chicken ie
-
enumerateDevices()
Enumerates available media input and output devices such as microphones, cameras, headphones, etc. Returns an array of unavailable device information; -
getDisplayMedia(opitons)
is called and prompts the user to select and grant permission to capture the display, or a portion thereof, such as a window, as aMediaStream
( media content stream), that is,share screen content
;
Example of parameteroptions
: getDisplayMedia({ video:true, audio:false })
Note:video:true
means that the content stream contains a video track;audio:false
means that the content stream does not contain an audio track, see all parameters -
getSupportedConstraints()
The method returns the list of constraints supported by the user agent (ie browser), the data format is an object dictionary, the key is the attribute of the constraint, and the value is true (because the return are all supported constraints, all true). See more information on how constraints work -
The
getUserMedia(options)
method asks the user whether to allow the use of media input, that is,calls functions such as recording video or recording
, and the media input will generate a Tracks of the requested media type, including video tracks (produced by hardware or virtual video sources, such as cameras, video recording devices, screen sharing services, etc.), audio tracks (similarly produced by physical or virtual audio sources such as microphones, A/D converter, etc.), and possibly other track types.
Parameteroptions
: getUserMedia({ video:true, audio:false })
Note: This parameter has only two attributes, video and audio, which grant permission to record video and audio. -
The
selectAudioOutput()
method prompts the user to select a specific audio output device, such as speakers or headphones.
//enumerateDevices() enumerate available media async function getMediaDevices() {<!-- --> if (!navigator.mediaDevices?.enumerateDevices) {<!-- --> console.log("enumerateDevices() not supported."); } else {<!-- --> // List cameras and microphones. let mediaDevicesList; try {<!-- --> mediaDevicesList = await navigator. mediaDevices. enumerateDevices(); } catch (err) {<!-- --> console.error(`Error: ${<!-- -->err}`); } return mediaDevicesList; } } //getDisplayMedia() screen sharing async function startCapture(displayMediaOptions) {<!-- --> let captureStream; try {<!-- --> captureStream = await navigator.mediaDevices.getDisplayMedia( displayMediaOptions ); } catch (err) {<!-- --> console.error(`Error: ${<!-- -->err}`); } return captureStream; } //getUserMedia() Start recording video/recording async function startMediaInput(displayMediaOptions) {<!-- --> let stream = null; try {<!-- --> stream = await navigator.mediaDevices.getUserMedia(constraints); /* use the stream */ } catch (err) {<!-- --> /* handle the error */ } } //selectAudioOutput() select audio output device function selectAudioOutput(displayMediaOptions) {<!-- --> if (!navigator.mediaDevices.selectAudioOutput) {<!-- --> alert("selectAudioOutput() not supported."); return; } // Display prompt and log selected device or error navigator.mediaDevices .selectAudioOutput() .then((device) => {<!-- --> list3.innerText = JSON.stringify(device) console.log(`${<!-- -->device.kind}: ${<!-- -->device.label} id = ${<!-- -->device.deviceId}`); }) .catch((err) => {<!-- --> console.error(`${<!-- -->err.name}: ${<!-- -->err.message}`); }); }
jcode
5. permissions (permission management)
The
Navigator.permissions
property returns an objectPermissions
that can be used to query and update the permission status of APIs covered by the Permissions API.
The Permissions object has three instance methods: query(), request(), requestAll(), revoke()
Note: The request(), requestAll(), revoke() methods are not available!
Compatibility: ie again!
query()
is used to query the permission status of the specified permission, for examplenavigator.permissions.query({ name: " camera" })
.
The permissions that can be queried are:camera, clipboard-read, clipboard-write, geolocation, microphone, notifications, persistent-storage, gyroscope , push push notification
6. WakeLock (screen wakeup)
WakeLock
browsers attempt to prevent the device screen from dimming, shutting off completely, or displaying a screensaver when auto-screen off is enabled
Compatibility: General compatibility, use with caution!
navigator.wakeLock keeps the screen awake:
let lock; document.addEventListener("click", async () => {<!-- --> try {<!-- --> if (lock) {<!-- --> lock. release(); return; } lock = await navigator.wakeLock.request("screen"); lock.addEventListener("release", () => {<!-- --> lock = null; }); } catch (err) {<!-- --> console.log(`${<!-- -->err.name}, ${<!-- -->err.message}`); } });
7. userActivation (check whether the user interacts)
userActivation
Returns aUserActivation
object that contains information about the user activation state of the current window. This object has two properties: isActive, hasBeenActivePurpose: Commonly used to check whether a user gesture has been performed recently or to check whether a user gesture has been performed before
Compatibility: not supported by IE, only supported by Safari version 16.4 and above
isActive
is used to determine theshort-term activation status
, that is, to check whether the user has recently interacted with the page. Every interaction between the user and the page will make the page in the this state. But this state has a “validity period”. If the user does not interact with the page within a period of time after the interaction, this state will expire. The specific validity period is determined by the browser, for example, chrome is 5 seconds.hasBeenActive
is used to determine thesticky activation status
, that is, to check whether the user has interacted with the page, as long as the interaction is once, it will always be in this state.
if (navigator. userActivation. isActive) { // For example, continue to request to play media } if (navigator. userActivation. hasBeenActive) { // For example, continue to play the animation automatically }
8. serial (serial port communication, peripheral equipment connected to the computer)
serial
provides properties and methods to find and connect serial ports from web pages.
Purpose: It can communicate with the hardware through the serial port on the web side
Compatibility: safari, Firefox, IE do not support
Method:
- The
requestPort()
method obtains the authorized serial port, prompts the user to select a device, and refuses if no device is selected (this method must be called when the user activates it). getPorts()
Indicates the serial ports connected to the host to which the source has access.
Event:
connect()
event: an event triggered when a port is connected to a device.disconnect()
Event: Event triggered when the port is disconnected from the device.
navigator.serial.addEventListener("connect", (e) => {<!-- --> // Connect to `e.target` or add it to a list of available ports. }); navigator.serial.addEventListener("disconnect", (e) => {<!-- --> // Remove `e.target` from the list of available ports. }); navigator.serial.getPorts().then((ports) => {<!-- --> // Initialize the list of available ports with `ports` on page load. }); button.addEventListener("click", () => {<!-- --> const usbVendorId = 0xabcd; navigator.serial .requestPort({<!-- --> filters: [{<!-- --> usbVendorId }] }) .then((port) => {<!-- --> // Connect to `port` or add it to the list of available ports. }) .catch((e) => {<!-- --> // The user didn't select a port. }); });
9. Other attributes
Attribute/Method | Description |
---|---|
userAgent | Returns the user agent string of the current browser, userAgent is configurable |
appName | browser full name |
cookieEnabled | Returns a Boolean value to indicate whether cookies are enabled on the current page |
deviceMemory | Returns the approximate device memory capacity in GB |
maxTouchPoints | Returns the maximum number of simultaneous touch points supported by the current device. |
online | Returns a Boolean value indicating whether the browser is connected to the Internet |
userAgent | Returns the user agent string of the browser |
pdfViewerEnabled | Whether the browser supports loading PDF files, if it does not support online viewing, download PDF |
10. Conclusion
Let me reiterate: This article only records some attributes of the navigator, and I will record its method in the next article~
Comprehension: In the process of understanding navigator, I discovered many new continents. It turns out that the web can already realize many advanced functions, such as connecting VR devices. Although many of them are experimental functions, after understanding them, we can greatly broaden our horizons. front view. It’s not that when the demand is raised, I don’t know whether the front end can be realized
Here’s a list of all the Web APIs-too many to piss your head off.
I advise everyone, don’t think about the death of the front end all day long. The death of the front end is not a human being It’s a big deal to find a restaurant to serve food in the front ()