The deviceorientation event in JavaScript is not triggering on Chrome for Android

  1. I am attempting to activate the deviceorientation event in JavaScript, but it's not firing on my Android device. If you'd like to review the event documentation, please click here and view this image: https://i.sstatic.net/HkcOQ.png
window.addEventListener('deviceorientation', function(event) {
  console.log(event.alpha + ' : ' + event.beta + ' : ' + event.gamma);
});
  1. It works perfectly in Chrome desktop and the event is triggering as expected. (To test in Google Chrome, go to Inspect -> Customize and control devTools -> more Tools -> sensors -> orientation (turn it on and rotate virtual device).

3. However, if I open the link on any Android device, the event doesn't work. I'm unable to see any console logs or alerts. Are there additional settings required to access orientation details on an Android?

Any help is greatly appreciated.

Answer №1

To access the webpage, make sure to use https:// protocol, regardless of whether you have an SSL certificate installed or not.

Answer №2

Presently, I am encountering a similar issue. The deviceorientation events work in Chrome desktop, but not in Chrome Android. Conversely, in FireFox, it's the opposite.

The reason for this behavior is unknown to me. However, I can offer a basic troubleshooting step and a potential solution to make it function in both Chrome and FireFox on desktop and Android.

To start, try uninstalling your Chrome browser or just its updates, then reinstall. This simple action resolved the deviceorientation issue on my phone.

The alternative solution is as follows:

You may utilize one of the OrientationSensors, specifically the AbsoluteOrientationSensor and RelativeOrientationSensor, from the Sensor APIs to ensure compatibility across Chrome Android while still retaining the fallback of deviceorientation where applicable, like Chrome desktop and FireFox Android. Sensor APIs are currently only accessible in Chrome. These Sensor APIs necessitate secure contexts such as https pages (more details at https://www.w3.org/TR/secure-contexts/). Speaking about device orientation measurement on the web, these sensor APIs distinguish between absolute orientation (relative to Earth's true North) and relative orientation. You can also achieve absolute orientation using the deviceorientation event by ensuring its absolute property is set to true. If the property is false, it indicates that your device lacks a magnetometer in theory. Additionally, mobile Safari does not consider this property. Instead, it uses webkitCompassHeading, mentioned in the Apple Developer documentation and MDN, although not explicitly listed in the specification. Moreover, the deviceorientation event specification includes references to additional features like the compassneedscalibration Event and deviceorientationabsolute Event, which seem overlooked by developers.

In my personal view, this process should be more straightforward. A simple boolean value indicating whether the orientation is absolute or relative would suffice, with the alpha value consistently representing the compass angle from either true North or magnetic North. Although the introduction of Sensor APIs promises simplification, their widespread implementation is yet to be seen.

When combined with the Permissions API, the usage should resemble the following example excerpted from MDN:

const sensor = new AbsoluteOrientationSensor();
Promise.all([navigator.permissions.query({ name: "accelerometer" }),
             navigator.permissions.query({ name: "magnetometer" }),
             navigator.permissions.query({ name: "gyroscope" })])
       .then(results => {
         if (results.every(result => result.state === "granted")) {
           sensor.start();
           ...
         } else {
           console.log("No permissions to use AbsoluteOrientationSensor.");
         }
   });

This API provides a quaternion, which is highly beneficial for orientations and rotations, especially when working with 3D engines like three.js or babylonjs. Utilize the sensor's onreading event handler to obtain the quaternion and update object orientations in the render loop of your chosen 3D engine.

You can explore some examples through developer tools inspector, including an AbsoluteOrientationSensor demonstration lower down the page:

An earlier comment mentions the necessity of using HTTPS for deviceorientation events, as per the specifications outlined here: https://w3c.github.io/deviceorientation/#security-and-privacy. Nevertheless, based on my tests, these events function even on HTTP pages. Unfortunately, in certain scenarios like ours, they might fail even within an HTTPS environment.

In conclusion, navigating the realm of web development involving sensors can indeed be challenging. Hopefully, these insights prove helpful amidst the current complexities.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using Quaternion in THREE.js for Rotating and Translating Objects

I possess the following elements: a translation: [x1, y1, z1] a quaternion: [x, y, z, w] Is there a method to utilize the translation and quaternion to execute rotation and translation on a three.js mesh? Furthermore, is it possible to merge these in ...

collaborating with numerous JavaScripts

I am currently working on a project that involves several JavaScript functionalities such as an image viewer, carousel, and toggles. Now, I need to implement a pop-up form, but when I add the JavaScript for the pop-up, the entire page stops working. I wou ...

determine the proportion of the item

My function is supposed to map an object to create new keys. The new key "percent" is meant to calculate the percentage of each value of the key "data". It should be calculated as the value divided by the sum of all values. However, for some reason, it&apo ...

What is the best way to reveal the menu options by tapping on the top left icon?

Seeking guidance on how to activate the menu by clicking the top left corner icon. A sample code setup is available in Codepen through this link: https://codepen.io/RSH87/pen/rmgYbo. I require assistance with incorporating the JavaScript file into my React ...

Ensuring the correctness of phone numbers by validating them with country codes through the use of

I'm currently working on validating phone numbers using intl-tel-input, following the example provided at Below is the code snippet I've been using: var telInput = $("#phone"), errorMsg = $("#error-msg"), validMsg = $("#valid-msg"); // initial ...

Passing data from parent AngularJS directive to child sub-directive

While working on my Angularjs project, I encountered an issue with directive nesting and passing variables. To start, I created a directive called 'header': .directive('header', [function() { return { restrict: 'E&apo ...

Using JavaScript to change text contained within an HTML element into a separate HTML element

Can JavaScript or JQuery make this transformation possible, or is there another method to achieve it? If we have an HTML file structured like this <div> <p>Hello World</p> </div> And the goal is to convert "World" into a stan ...

Angular 2: The window.crypto.subtle.importKey function functions properly on 'localhost' but encounters issues on an 'ip' address

As a newcomer to Angular 2, I am working on creating a login form that encrypts and sends the user's emailid and password to the server. I have successfully implemented AES-ECB using AES-CTR from the following link: https://github.com/diafygi/webcry ...

Easiest way to retrieve data with Backbone.js collections

I am currently attempting to download, parse, and display a list from the XML data received from my server using Backbone.js. Below is the code snippet: var Item = Backbone.collection.extend({ url: "http://myurl.com/file.xml", parse: function() { ...

Maximizing code efficiency with jQuery toggleClass

After creating a code to validate input fields for empty values, I've come to realize that using jQuery toggleClass could potentially enhance or optimize it. However, I'm stuck on how to go about implementing this improvement. Any assistance woul ...

Efficiently verifying elements within an array

I have a roster of students categorized based on their activity status - some are active, while others are inactive. var allActive = [{id: 1, active: true}, {id: 2, active: true}, , {id: 3, active: true}]; var someNot = [{id: 4, active: true}, {id: 5, act ...

When the parent component in React JS rerenders, the props are not automatically passed down to the child

I have come across similar questions in the past, but I have not found any answers that directly address the issue I am facing in my scenario. In my case, there is a parent component that passes a property to a child component's state. Depending on t ...

Ways to remove newly added tasks using JavaScript function?

I have an existing list of li elements in my HTML that can be deleted using JavaScript. However, whenever I add a new li, the delete function no longer works on the newly added item. I suspect the issue lies within the current implementation of the for loo ...

Exploring the selected object in VueJs

I am attempting to showcase a fullName function using the selected value HTML : <div id="test"> <h1>{{ sayHello }}</h1> <select v-model="selected"> <option v-for="person in persons" v-bind:value="person.about"> {{ per ...

What is the process for adjusting the code to manage the labels of specific buttons?

There is a code $("button").click(function() { var btn = this; if (btn.loaded) { $(btn).prev("div").html(btn.originalContent); btn.loaded = false; $(btn).text('Get Dynamic chart'); } else { btn.originalConte ...

The React getTime() method does not properly update the state

I am attempting to update the state of the component Demoss using an external function called getTime(). My goal is to start updating the time in the state time when the page loads. In order to achieve this, I have called it in the componentDidMount meth ...

What is the mechanism behind angular2's spa routing functioning seamlessly without the need for the hash character in the url?

During my experience with the Angular2 "Tour of Heroes" tutorial, I made an interesting observation about how their single page application router functions without a trailing hash symbol (#) in the URL. This differs from the Kendo SPA router, which typica ...

Creating dynamic links within HTML through real-time updating

In my application, I have a feature that generates a list of words and converts them into clickable links. When the user clicks on a link, I want to extract the {{word.name}} from the HTML link without navigating to a new page. I simply need to retrieve th ...

Guide to testing Vuex Mutations with Vue-test-utils and Jest

I have reviewed a few tutorials on mocking and testing Vuex actions, but I have struggled to implement them successfully on my own. Despite following the steps outlined in the links provided, I consistently encountered an issue where toHaveBeenCalled would ...

Convert an array of string values into a JSON format

I need help with converting an array stored in my database to a more user-friendly format. Currently, it is saved as follows: ["size:medium","height:10cm"] This format makes it difficult to display in a table. I am wondering if there is a way to conver ...