Foreword
The book continues from the previous article. In the previous article, I introduced some properties of the bom object navigator API portal, so this article will continue to introduce some of its “magic” method APIs.
Again:
People are always afraid of what they don’t understand
For most front-end boys, in fact, they only need to know that there is such a thing. Most of the tricky requirements, in fact, the most difficult thing is that we can’t think of the way to realize it, and it’s a later story if we don’t know how to use it (won’t be able to Baidu cv)
1. sendBeacon() | Buried point data reporting
navigator.getBattery()
can be used to asynchronously transfer small amounts of data to a web server by making a network request. It is usually used to report buried point data, which solves some problems in the traditional data reporting method of buried points (it cannot ensure that the request is completed when the page is closed, etc.).
Because using thesendBeacon()
method causes the user agent toasynchronously
send data to the server when it gets the chance (data transmission is guaranteed to complete
), anddoes not affect the closing of the page or the loading of the next page
.
Example Code >>>
document.addEventListener('visibilitychange', function logData() {<!-- --> if (document.visibilityState === 'hidden') {<!-- --> navigator.sendBeacon('/log', analyticsData); } });
Parameters >>>
url
: interface address;data
: The data to be sent can be data of the typeArrayBuffer, ArrayBufferView, Blob, DOMString, FormData, URLSearchParams
.
2. getBattery() | Battery information monitoring
The
navigator.getBattery()
method is used to get information about the system battery. Return a promise object, and then resolve to get theBatteryManager
object, which provides some information about the battery and some methods to monitor the battery status.
Example Code >>>
navigator.getBattery().then((battery) => {<!-- --> console.log('battery information', battery) console.log('is the battery charging', battery.charging) battery.addEventListener("chargingchange", () => {<!-- --> console.log(battery.charging?'start charging':'stop charging') }); });
Properties >>>
charging
: whether the battery is charging;chargingTime
: The remaining time (in seconds) before the battery is fully charged, or 0 if the battery is already fully charged;dischargingTime
: the remaining time in seconds before the battery is fully discharged and the system shuts down;level
: battery power (value is 0~1), power percentage.
Method >>>
chargingchange
: triggered when the battery charging state is changed;chargingtimechange
: Triggered when the battery charging time (chargingTime attribute) is changed;dischargingtimechange
: Triggered when the battery discharge time (dischargingTime attribute) is changed;levelchange
: Triggered when the battery level (level property) changes.
3. registerProtocolHandler() | Make calls, etc.
navigator.registerProtocolHandler()
The method is used to open a specific URL (aka protocol) for the protocol program specified by website registration, such as the mail protocolmailto:URL code>, telephone protocol
tel:URL
, if it has already been registered, the query pop-up window will not be displayed again.
unregisterProtocolHandler()
The method is used to cancel the protocol handler, the parameters are scheme, url
Example Code >>>
const scheme = 'tel' const url = `${<!-- -->Current website URL}?uri=%s` //Example: const title = 'Allow this site to handle [scheme] links? ' navigator.registerProtocolHandler(scheme,url,title);
Parameters >>>
scheme
: The name of the protocol that the current site is expected to handle. The protocols that can be processed includebitcoin, mms, geo, news, mailto, ssh, tel, etc.
;url
: The website address of the registration agreement, the format iscurrent website URL + '?uri=%s'
, note that this string must Contains a "%s" placeholder to be replaced by an escaped link to the document to be accepted (maybe a real URL, or a phone number, email address, etc.);title
: The title of the pop-up window when asking the user for the registration agreement.
4. requestMIDIAccess() | Electronic musical instrument communication
The
navigator.requestMIDIAccess()
method is used to communicate between electronic musical instruments, computers and other devices. It allows sending messages from one device to another.
Example Code >>>
if (navigator.requestMIDIAccess) {<!-- --> navigator.requestMIDIAccess().then(success, failure); } // success callback function success (access) {<!-- --> // Get a list of available MIDI controllers console. log(access) // input represents any MIDI device you have connected to your computer const inputs = access.inputs.values(); const outputs = access.outputs.values(); } // failure callback function failure () {<!-- --> console.error('cannot access your midi device') }
Parameters >>>
sysex
: boolean type, the default value is false. Set to true to allow sending and receiving system exclusive system operating system messages;software
: boolean type, the default value is false. Set to true to allow the system to use any installed software synthesizers.
5. share() | Share data
navigator.share()
Call the device's local sharing mechanism to share data such as text, URL or file. Available share targets are device dependent and may include the clipboard, contacts and email applications, websites, bluetooth, and more.
Example Code >>>
const shareData = {<!-- --> title: "Share", text: "Learning is like sailing against the current, if you don't advance, you will retreat", url: "https://developer.mozilla.org", }; navigator. share(shareData)
6. vibrate() | Device vibration
The
navigator.vibrate()
method causes the device to vibrate (when vibration hardware is present on the device). If a vibration pattern is already in progress when this method is called, the vibration will restart.
Example Code >>>
navigator.vibrate(200); // Vibrate for 200ms navigator.vibrate([ 100, 30, 100, 30, 100, 30, 200, 30, 200, 30, 200, 30, 100, 30, 100, 30, 100, ]); // Vibrate "SOS" in Morse code
Parameters >>>
pattern
: The duration of the vibration or pause. When an array, each value represents the number of milliseconds to indicate an alternate vibration or pause.
7. getGamepads() | Gamepad
The
navigator.getGamepads()
method is used to get the gamepads connected to the device and returns an array.
Example Code >>>
window.addEventListener("gamepadconnected", (e) => {<!-- --> const gp = navigator.getGamepads()[e.gamepad.index]; console. log( `Gamepad connected at index ${<!-- -->gp.index}: ${<!-- -->gp.id} with ${<!-- -->gp.buttons .length} buttons, ${<!-- -->gp.axes.length} axes` ); });
10. Conclusion
Although many APIs of navigator are still in the experimental stage, the compatibility is not very good, but I think the compatibility of these APIs is directly proportional to the compatibility of the product manager's brain circuit with the market, the product can propose these tricky requirements , you should think about and accept its compatibility issues.
Some students may ask: The product doesn't think about this at all.
Then you tell him: *****