javascriptsensorsgoogle-cardboard

Detect Google Cardboard Magnetic Button Click in Javascript


With refering to Detecting Magnetic Button on Cardboard in C# is there anyway to access the magnetic cardboard button within Javascript in a browser of a mobile phone?

cheers Stefan


Solution

  • I was finally able to solve the problem myself. Fortunately time and a bit of luck helped for solution (it wouldn't have been possible by the time I was actually asking for it).

    The solution is based on the "Generic Sensor API" proposed by the W3C and in particular the implementation for the Magnetometer API.

    see the following specs - https://developers.google.com/web/updates/2017/09/sensors-for-the-web - https://www.w3.org/TR/generic-sensor/ - https://w3c.github.io/magnetometer/

    However, there are some caveats:

    I have extracted the following code from my much more complex code. I hope I did not overlook anything.

    this.lastSensorX = 0;
    
    try {
      this.sensor = new Magnetometer();
      if (this.sensor!==undefined) {
           this.sensor.start();
      }
    } catch(err) {
                console.log("Magnetometer not supported. Make sure you configure chrome://flags/#enable-generic-sensor-extra-classes and deliver via HTTPS.");
    }
    
    ....
    
    // Check major differences on Magnetometer and identify this as a button-click
    
    if (this.sensor !== undefined) {
      this.sensor.onreading = () => {
         var delta= this.sensor.x-this.lastSensorX;
          
         if (delta > 100 ) {
               // do whatever you want to do, in case the cardboard magnet has been "clicked"
         }
         this.lastSensorX = this.sensor.x;
      }
      
      this.sensor.onerror = event => console.log(event.error.name + " (Magnetometer): ", event.error.message);
    
    }

    I used the above snipped in my own application it it works perfectly.