fromShare 8 interesting and useful apis

preface

In daily development, we always deal with various apis. Our name is front-end engineer, but actually we are API call engineer. In this article I’m going to share 8 interesting apis, and if you add a little bit of fun to the front end by reading this article, it’s an encouragement to me.

These apis, when used properly, can improve the friendliness of your application.

I’ve posted sample code for these apis on Github and can clone the code to run locally if you are interested. Please give a star support.

Apis can also be fun

First look at the renderings:

1. Monitor screen rotation change interface: orientationChange

Definition:

This API exposes your phone’s landscape to those who need to know.

Use:

screenOrientation: function(){ let self = this; let orientation = screen.orientation || screen.mozOrientation || screen.msOrientation; window.addEventListener("onorientationchange"in window ? "orientationchange" : "resize", function() { self.angle = orientation.angle; }); }, copy the codeCopy the code

Orientation. Angle Screen orientation 0 portrait 90 Left portrait -90/270 Right portrait 180 Reverse

With this API we can add some actions or style changes to landscape and portrait.

If only style changes can be monitored by media query:

/* @media screen and (orientation: portrait) {// some CSS code} /* @media screen and (orientation: portrait) {// some CSS code} /* @media screen and (orientation: portrait) Landscape) {// some CSS code} Copy codeCopy the code

2. Battery status: Navigator.getbattery ()

Definition:

This API can expose your phone’s battery status to anyone who needs to know.

This API returns a Promise object that gives a BatteryManager object containing the following information:

ChargingTime If charging is in progress, Charge time readable property dischargingTime Remaining battery readable property Level Percentage of remaining battery readable property onChargingChange Monitor change of charging status monitor event onChargingTimechange Monitor change of chargingtime monitor event ondisch Argingtimechange listens for changes in the amount of battery time available. Onlevelchange Listens for changes in the percentage of battery remaining.

getBatteryInfo: function(){ let self = this; If (navigator.getbattery){navigator.getbattery (). Then (function(battery) {// Determine whether self.batteryInfo = battery ? ${battery.level * 100}% ':' No charge: ${battery.level * 100}% '; Battery. AddEventListener ('chargingchange', function(){self.batteryInfo = battery. ${battery.level * 100}% ':' No charge: ${battery.level * 100}% '; }); }); }else{self.batteryInfo = 'Battery status interface not supported '; }}, copy the codeCopy the code

3. Make your phone vibrate: window.navigator.vibrate(200)

Definition:

This API allows your phone to vibrate as you wish.

Use:

Vibration is used in many games. For example, in “Joy Fight landlord”, the landlord’s mobile phone will vibrate after he blows up the king, which is quite reasonable to express the landlord’s showy mood.

Example code is as follows:

vibrateFun: function(){ let self = this; if( navigator.vibrate ){ navigator.vibrate([500, 500, 500, 500, 500, 500, 500, 500, 500, 500]); }else{self.vibrateInfo = "Your device does not support vibrateInfo "; } <! -- // Clear navigator. Vibrate (0); SetInterval (function() {navigator.vibrate(200); }, 500); -->}, copy codeCopy the code

4. Current language: Navigator.Language

Definition:

This API tells you what language to use at the moment.

If you need to do multilingual adaptation like I did, this API might give you a good idea.

Use:! [](data:image/svg+xml; utf8,
< SVG XMLNS =”www.w3.org/2000/svg” version=”1.1″ width=”386″ height=”180″>
) The value returned by different browsers is slightly different. FunctiongetThisLang (){const langList = [‘cn’,’hk’,’ TW ‘,’en’,’fr’]; const langListLen = langList.length; const thisLang = (navigator.language || navigator.browserLanguage).toLowerCase(); for( let i = 0; i < langListLen; i++ ){ let lang = langList[i]; If (thislang.includes (lang)){return lang}else {return’en’}}} copy the code

Different languages should correspond to different language copywriting.

5. Networking status: Navigator.online

Definition:

This API can tell you if your device’s network status is connected.

Use:

For example, I logged in to the Nuggets this morning to read an article, but it was time to eat before I finished reading it. I must have chosen to continue reading after lunch because I love learning so much.

Thirty minutes later…

Back to the company after dinner, open the computer to continue to read the article, read the plan to point the praise, found to give this hint:! [](data:image/svg+xml; utf8,
< SVG XMLNS =”www.w3.org/2000/svg” version=”1.1″ width=”505″ height=”189″>

At this point we can use this API to tell the user exactly “your network is down, please check”. Will users have a better experience?

The code is as follows:

mounted(){ let self = this; window.addEventListener('online', self.updateOnlineStatus, true); window.addEventListener('offline', self.updateOnlineStatus, true); }, methods: { updateOnlineStatus: function(){ var self = this; self.onLineInfo = navigator.onLine ? "online" : "offline"; },} copy the codeCopy the code

Note: Navigator. onLine will only return false if the machine is not connected to a LAN or router, but true otherwise. Navigator. onLine returns true even if the router is not connected to the Internet.

6. Page editable: contentEditable

Definition:

This API makes all elements of the page editable, turning the browser into your editor.

Use:

  1. You can enter it in the address bardata:text/html, <html contenteditable>The browser becomes an editor.

! [](data:image/svg+xml; utf8,
< SVG XMLNS =”www.w3.org/2000/svg” version=”1.1″ width=”648″ height=”390″>

Requirements – The page needs a text entry box.

  1. The text input box has a default text prompt by default
  2. The height of the text box in the input state will automatically expand with the text content

For such needs we can use

instead of the

But contentEditable=’true’ is not a placeholder.

I usually use the following scheme, changing the class after typing:

<div class='haveInput' contentEditable='true' placeholder=' please input '></div> // CSS styles. haveInput:before {content: attr(placeholder); display: block; color: #333; } Duplicate codeCopy the code

7. Browser active window listener: window.onblur & window.onfocus

Definition:

These two apis indicate that the window is out of focus and the window is active, respectively.

The window.onblur event is triggered when you browse other Windows, minimize the browser, click on other programs, etc.

Return to the window, and the window.onfocus event will fire.

Use:

mounted(){ let self = this; window.addEventListener('blur', self.doFlashTitle, true); window.addEventListener('focus', function () { clearInterval(self.timer); Document. title = 'wechat '; }, true); }, methods: { doFlashTitle: function(){ var self = this; self.timer = setInterval( () => { if (! Self. FlashFlag) {document.title = ""; } else {document.title = '微信 (${self.infonum})'; } self.flashFlag = ! Self.flashflag}, 500)},} copy the codeCopy the code

8. Fullscreen API

Definition:

This API enables the page you open to be displayed in full screen, with no content outside the page displayed on the screen.

Use:

Element. RequestFullscreen () method is used to make asynchronous requests make elements into full screen mode.

Calling this API does not guarantee that an element will enter full-screen mode. If the element is allowed to enter full-screen mode, the Document object receives a fullScreenchange event notifying the caller that the current element has entered full-screen mode. If the full-screen request is not approved, a FullScreenError event is received.

The FullScreenChange event is triggered when you enter or exit the full-screen mode. You can listen in on the event and do what you want.

fullScreenFun: function(){ let self = this; var fullscreenEnabled = document.fullscreenEnabled || document.mozFullScreenEnabled || document.webkitFullscreenEnabled || document.msFullscreenEnabled; if (fullscreenEnabled) { let de = document.documentElement; If (self.fullScreenInfo === 'open fullscreen '){if(de.requestFullScreen){de.requestFullScreen (); }elseif( de.mozRequestFullScreen ){ de.mozRequestFullScreen(); }elseif( de.webkitRequestFullScreen ){ de.webkitRequestFullScreen(); } else {if(document.exitFullScreen){document.exitFullscreen(); }elseif( document.mozCancelFullScreen ){ document.mozCancelFullScreen(); }elseif( document.webkitCancelFullScreen ){ document.webkitCancelFullScreen(); } self.fullScreenInfo = 'open fullscreen'}} else {self.fullScreenInfo = 'browser is not currently full screen '; }} Copy the codeCopy the code

Related:

  1. Document. FullscreenElement: the current element in a state of full screen elements
  2. Document. FullscreenEnabled: tag fullscreen current is available
  3. Document.exitfullscreen (): Exits full screen