Devtools Guide: Using Sensors for Beginners
Developer tools provided by browsers are an invaluable asset for web developers. They enable us to quickly diagnose issues, edit HTML in real-time, and iterate on our web applications more efficiently. In this article, we will explore one such powerful tool: the Sensors tab in Chrome DevTools.
Scenario
Let's think of a scenario where we can use sensors.
We have a web app where we need to display a greeting to the user based on the time of day. The requirements are as follows:
User should be able to see contextual greeting based on time of the day.
1. "morning"
if the time is between 00:00 to 11:59
2. "afternoon"
if the time is between 12:00 to 16:59
3. "evening"
if the time is between 17:00 to 23:59
Let's write some code for this:
Whenever we write code for such requirements, it is better to create a pure function. A pure function provides the same output for the same arguments and does not depend on any global variables.
function giveContextualGreeting(date = new Date()) {
const hours = date.getHours();
if(hours >= 0 && hours < 12)
return "morning"
else if(hours >= 12 && hours < 17)
return "afternoon"
else
return "evening"
}
To test if this is working as intended, you can do one of the following:
Push your code to a source code management tool and ask a teammate in a different location to test it.
Wait for the relevant time and test the function.
Both methods take a lot of time and can slow down your app development.
To overcome this, you can make use of sensors.
Sensors
The Sensors tab allows you to emulate sensor input from various devices, providing a convenient way to test how your website responds to different sensor data. This is particularly useful when building features that rely on user location, device orientation, or touch input.
We will take a look at how we can override geolocation to simulate the user's location, including custom coordinates or preset cities
Lets run the function in console of the browser.
This returns the result for your location. Now to check for other location, open sensors in devtools.
Open the "Inspect" window - right click and select inspect from the list or press Command+Shift+I on mac and Control+Shift+I on Windows, Linux or Chromebook.
Open Sensors - press Command+Shift+P on mac and Control+Shift+P on Windows, Linux or Chromebook.
You can select one of the options
Lets select "Tokyo"
Lets select "Mountain View"
Now you are done with the testing the function without having to wait for time or someone else in different location to help you out.
That's all for this article. Thanks for reading.
Subscribe to my newsletter
Read articles from Tahir Ahmed directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by