Key Points
Nowadays, we (at least should) realize that the mobile market is crucial when developing anything for the web.
For many years, discussions and opinions on native applications and web applications have vary greatly, and it has been controversial which one is better. Regardless of your point of view, it is true that native mobile applications have been able to access hardware components that web pages cannot access in the past. But is this gap still valid today? Has web technology developed enough to allow us, as developers, to encode only using HTML, CSS, and JavaScript?
In this article, I will introduce some JavaScript APIs that allow your web pages to access the hardware components of your mobile device, or enhance the functionality of your web applications on your mobile device.
Battery Status API
Battery Status API provides information about the battery level or status of the system. With this API, you can know if the battery is being charged, how long it will be before the battery is fully discharged, or just its current capacity. These details can be accessed through four properties belonging to the object. This API also defines events that can be triggered when the above properties change. window.navigator.battery
As of this writing, the Battery Status API is only supported by Firefox, but it is very easy to detect support for this API, as shown below:
if (window.navigator && window.navigator.battery) { // API 受支持 } else { // 不受支持 }
if (window.navigator && window.navigator.battery) { // API 受支持 } else { // 不受支持 }
If you want to try this API, we have a demo for you. If you want to research further, we have introduced the Battery Status API on SitePoint here.
Web Notification API
On mobile devices, we are familiar with the concept of notifications, and many applications that have been installed on the device implement notifications. On the web, websites implement them in different ways. Think about Google and Twitter, they both have notification mechanisms, but they implement them differently.
The Web Notification API is an API created for this purpose to normalize how developers notify users. Notifications allow users to remind a user of an event outside of the context of the webpage, such as email delivery. While developers create notifications in the same way, the specification does not describe how and where the UI should display them. This means we will see different styles on different browsers. For example, on mobile devices, we might see them in the notification bar.
TheWeb Notification API is exposed through the window
attribute of the Notification
object. It is a constructor that allows us to create notification instances. To create a new notification, we can write the following code:
// 打印电池是否正在充电 console.log("电池" + (navigator.battery.charging ? "" : "未") + "充电");
Currently, Chrome, Firefox, and Safari support this API. Mobile browsers that support the Web Notification API include Firefox, Android 4.4, and Blackberry. Have you seen something strange? Chrome Mobile does not support this API! Sad but it is true.
Because browsers that support this API cover more than half of the market, but to ensure that our JavaScript code does not try to call unsupported methods, we have to test the support situation. We can do this using the following code snippet:
var notification = new Notification('收到电子邮件', { body: '您收到了一封电子邮件。立即阅读!' });
Excited by this API? Very good! You can learn more in the article Getting started with the Web Notification API, and you can also try out the live demo.
Proximity Sensor API
The Proximity Sensor API is a JavaScript API that we can use to detect the distance between an object and the device running a web page. The distance is measured by the proximity sensor (if your device has a proximity sensor). The proximity sensor API does not provide attributes or methods, only triggers two events on the window
object. We can listen to them to perform operations. The first event deviceproximity
provides information about the actual distance between the device and nearby objects, while the second event userproximity
specifies only whether there are objects nearby.
The only browser that supports this API is Firefox (Desktop and Mobile), starting with version 15. Unfortunately, since many laptops and desktops do not have proximity sensors, we mainly target mobile devices.
Detection of support for this API:
if ('Notification' in window) { // API 受支持 } else { // 不受支持 }
A simple example of use is as follows:
if ('ondeviceproximity' in window) { // API 受支持 } else { // 不受支持 }
If you want to learn more about the proximity sensor API, I wrote an article titled "Beginning with the proximity sensor API." If you want to actually do this, you can use this demo.
Vibration API
Vibration API is a very simple API that contains a method that allows us to make devices vibrate. One obvious use is in the game where we can reproduce the effects introduced by some consoles a decade ago. However, this is not the only possible purpose of this API.
As I mentioned, the Vibration API only exposes a method called vibrate()
. The latter belongs to the window.navigator
object, in its simplest form, accepts an integer that specifies the number of milliseconds the device should vibrate.
Apart from Internet Explorer and Safari, this API is supported by all major browsers. Still, now may be a good time to use it for your next project. In fact, if it is supported, you will give the user a better experience (unless you abuse this feature). Detection support is very easy, as shown below:
if (window.navigator && window.navigator.battery) { // API 受支持 } else { // 不受支持 }
A very simple way to use the API is as follows:
// 打印电池是否正在充电 console.log("电池" + (navigator.battery.charging ? "" : "未") + "充电");
To learn more about this API, read the article "How to Use HTML5 Vibration API" and don't forget to try the demo.
Device Direction API
The last API I want to discuss is the Device Direction API. Detecting the orientation of the device is useful for a variety of situations, from navigation applications to games. This API defines several events that provide information about the physical orientation and movement of the device. This API is a W3C working draft, which means that the specification is unstable and we may expect some changes in the future.
The API exposes the following three events: deviceorientation
, devicemotion
and compassneedscalibration
. The first event is triggered when the accelerometer detects a change in the direction of the device. A second event is triggered every time the device accelerates or decelerates. The last event is triggered when the user agent determines that the compass needs to be calibrated.
Almost all major browsers (except Safari) support this API, but the support is partial or there are inconsistencies. For example, at the time of writing, few browsers support compassneedscalibration
events. So my suggestion is to test each event to see if it is supported. To test the existence of deviceorientation
events, you can write:
var notification = new Notification('收到电子邮件', { body: '您收到了一封电子邮件。立即阅读!' });
Or:
if ('Notification' in window) { // API 受支持 } else { // 不受支持 }
For example, if you want to test the devicemotion
event, you can write:
if ('ondeviceproximity' in window) { // API 受支持 } else { // 不受支持 }
If you want to use this API, we have a demo that you can use. If you want to learn it, we have the article "Using Device Orientation in HTML5".
Conclusion
In this article, I show you some APIs that can enhance mobile visitor web pages.
The use cases for these APIs are endless, it all depends on your imagination and the type of application or website you are developing. I hope you enjoyed this post, please let me know what other useful APIs you think may be.
Frequently Asked Questions about Mobile Web JavaScript API
The JavaScript API (Application Programming Interface) is a set of rules and protocols that allow different software applications to communicate with each other. They enhance mobile web pages by enabling mobile web pages to interact with device hardware and other software applications, thereby enhancing their functionality and user experience. For example, the JavaScript API can allow web pages to access the device's camera, geographic location, and even battery status. This creates more possibilities for developers to interact, engage and user-friendly mobile web pages.
Geolocation API is a powerful tool that allows you to access the geolocation of your device. To use it, you first need to check if the user's browser supports it. This can be done using the navigator.geolocation
property. If it returns true
, then you can use the getCurrentPosition()
method to get the user's current location. Remember to always obtain the user's permission before accessing the user's location data.
Battery Status API provides information about the battery status of the host device. This is very useful for optimizing the performance of a web page based on the battery level of the device. For example, when the battery is low, you can lower the update frequency or disable certain features to save power. To use this API, you can use the navigator.getBattery()
method, which returns a promise that resolves to a BatteryManager object.
Vibration API allows you to control the vibration mechanism of the host device. This is very useful for providing tactile feedback to the user. To use this API, you can use the navigator.vibrate()
method. You can pass a single value to vibrate a specific time, or pass a series of values to create vibration and pause modes.
The Ambient Light Sensor API provides information about the ambient light level of the device. This is useful for adjusting the brightness or contrast of a web page to improve readability under different lighting conditions. To use this API, you need to create a new AmbientLightSensor
object instance and then start sensing the light level using the start()
method.
Network Information API provides information about the device's network connection. This is very useful for optimizing the performance of a web page based on the network status. For example, when the network connection is slow, you can reduce the quality of your images or videos to ensure smooth loading. To use this API, you can use the navigator.connection
property, which returns a NetworkInformation object.
Device Direction API provides information about the physical orientation of the device. This is very useful for creating interactive experiences that respond to device movement. To use this API, you can add an event listener to the deviceorientation
event, which fires when the device orientation changes.
Page Visibility API allows you to detect when a web page is visible or hidden. This is useful for pausing or resuming activity based on the visibility of the page. For example, when the user switches to another tab, you can pause the video and resume the video when they return. To use this API, you can use the document.visibilityState
attribute and the visibilitychange
event.
Full Screen API allows you to display elements in full screen mode. This is very useful for providing a more immersive experience for videos or games, etc. To use this API, you can use the requestFullscreen()
method for any element to make it appear in full screen.
The Web Notification API allows you to display notifications to users. This is very useful for reminding users of important events, even if your page has no focus. To use this API, you first need to request the user's permission using the Notification.requestPermission()
method. If the user grants permission, you can create a new Notification object to display notifications.
The above is the detailed content of 5 JavaScript APIs to Empower Your Mobile Web Pages. For more information, please follow other related articles on the PHP Chinese website!