xref: /docs/en/application-dev/web/web-sensor.md (revision e41f4b71)
1# Using Motion and Direction Sensors
2
3The **Web** component can be connected to motion and orientation sensors through standard W3C APIs. When using the acceleration, gyroscope, and device motion event APIs, you need to declare the corresponding sensor permissions in the configuration file.
4
5- Add the acceleration permission in the **module.json5** file before using the acceleration and device motion event APIs.
6   ```
7   "requestPermissions":[
8      {
9        "name" : "ohos.permission.ACCELEROMETER"
10      }
11    ]
12   ```
13- Add the gyroscope permission to the **module.json5** file before using the gyroscope APIs.
14   ```
15   "requestPermissions":[
16      {
17        "name" : "ohos.permission.GYROSCOPE"
18      }
19    ]
20   ```
21For details about how to add sensor permissions, see [Declaring Permissions in the Configuration File](../security/AccessToken/declare-permissions.md).
22
23When connecting the **Web** component to the motion and orientation sensors, configure **onPermissionRequest()** to receive permission request notifications.
24
25You can obtain the motion and orientation sensors by calling the following standard W3C APIs in JavaScript.
26
27| API                     | Name        | Supported| Description              |
28| ------------------------- | ------------ | -------- | ------------------ |
29| Accelerometer             | Acceleration      | Yes    | -                  |
30| Gyroscope                 | Gyroscope      | Yes    | -                  |
31| AbsoluteOrientationSensor | Absolute orientation    | Yes    | -                  |
32| RelativeOrientationSensor | Relative orientation    | No  | Does not support by sensor data.|
33| DeviceMotionEvent         | Device motion event| Yes    | -                  |
34| DeviceOrientationEvent    | Device orientation event| Yes    | Obtains the absolute orientation.|
35
36**RelativeOrientationSensor()** is not configured since it is not supported. Therefore, this API cannot be used to listen for the relative orientation data of the device.
37
38Click buttons on the **index.html** page to listen for corresponding data. The example code is as follows:
39
40- Code on the application side:
41
42  ```ts
43  import { webview } from '@kit.ArkWeb';
44  import { abilityAccessCtrl, PermissionRequestResult } from '@kit.AbilityKit';
45  import { BusinessError } from '@kit.BasicServicesKit';
46
47  @Entry
48  @Component
49  struct WebComponent {
50    controller: webview.WebviewController = new webview.WebviewController()
51    aboutToAppear() {
52      // Enable web frontend page debugging.
53      webview.WebviewController.setWebDebuggingAccess(true);
54      // Create an **AtManager** instance, which is used for application access control.
55      let atManager = abilityAccessCtrl.createAtManager();
56      try {
57        atManager.requestPermissionsFromUser(getContext(this), ['ohos.permission.ACCELEROMETER', 'ohos.permission.GYROSCOPE']
58          , (err: BusinessError, data: PermissionRequestResult) => {
59          console.info('data:' + JSON.stringify(data));
60          console.info('data permissions:' + data.permissions);
61          console.info('data authResults:' + data.authResults);
62        })
63      } catch (error) {
64        console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`);
65      }
66    }
67
68    build() {
69      Column() {
70        Web({ src: $rawfile('index.html'), controller: this.controller })
71          .onPermissionRequest((event) => {
72            if (event) {
73              AlertDialog.show({
74                title: 'title',
75                message: 'text',
76                primaryButton: {
77                  value: 'deny',
78                  action: () => {
79                    event.request.deny();
80                  }
81                },
82                secondaryButton: {
83                  value: 'onConfirm',
84                  action: () => {
85                    event.request.grant(event.request.getAccessibleResource());
86                  }
87                },
88                autoCancel: false,
89                cancel: () => {
90                  event.request.deny();
91                }
92              })
93            }
94          })
95      }
96    }
97  }
98  ```
99
100- Code of the **index.html** page:
101
102  ```html
103  <!DOCTYPE HTML>
104  <html>
105  <head>
106      <meta charset="utf-8" />
107      <meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
108      <meta name="misapplication-tap-highlight" content="no" />
109      <meta name="HandheldFriendly" content="true" />
110      <meta name="MobileOptimized" content="320" />
111      <title>Motion and direction sensor</title>
112      <meta charset="UTF-8">
113      <style>
114          body {
115              font-family: Arial, sans-serif;
116          }
117      </style>
118      <script type="text/javascript">
119          function getAccelerometer() {
120              var acc = new Accelerometer({frequency: 60});
121              acc.addEventListener('activate', () => console.log('Ready to measure.'));
122              acc.addEventListener('error', error => console.log(`Error: ${error.name}`));
123              acc.addEventListener('reading', () => {
124                  console.log(`[doc_sensor]Accelerometer ${acc.timestamp}, ${acc.x}, ${acc.y}, ${acc.z}.`);
125              });
126              acc.start();
127          }
128
129          function getGyroscope() {
130              var gyr = new Gyroscope({frequency: 60});
131              gyr.addEventListener('activate', () => console.log('Ready to measure.'));
132              gyr.addEventListener('error', error => console.log(`Error: ${error.name}`));
133              gyr.addEventListener('reading', () => {
134                  console.log(`[doc_sensor]Gyroscope ${gyr.timestamp}, ${gyr.x}, ${gyr.y}, ${gyr.z}.`);
135              });
136              gyr.start();
137          }
138
139          function getAbsoluteOrientationSensor() {
140              var aos = new AbsoluteOrientationSensor({frequency: 60});
141              aos.addEventListener('activate', () => console.log('Ready to measure.'));
142              aos.addEventListener('error', error => console.log(`Error: ${error.name}`));
143              aos.addEventListener('reading', () => {
144                  console.log(`AbsoluteOrientationSensor data: ${ros.timestamp}, ${ros.quaternion}`);
145              });
146              aos.start();
147          }
148
149          function listenDeviceMotionEvent() {
150              removeDeviceMotionEvent();
151              if ('DeviceMotionEvent' in window) {
152                  window.addEventListener('devicemotion', handleMotionEvent, false);
153              } else {
154                console.log ("DeviceMotionEvent is not supported.");
155              }
156          }
157
158          function removeDeviceMotionEvent() {
159              if ('DeviceMotionEvent' in window) {
160                window.removeEventListener('devicemotion', handleMotionEvent, false);
161              } else {
162                console.log ("DeviceOrientationEvent is not supported.");
163              }
164          }
165
166          function handleMotionEvent(event) {
167              const x = event.accelerationIncludingGravity.x;
168              const y = event.accelerationIncludingGravity.y;
169              const z = event.accelerationIncludingGravity.z;
170              console.log(`DeviceMotionEvent data: ${event.timeStamp}, ${x}, ${y}, ${z}`);
171          }
172
173          function listenDeviceOrientationEvent() {
174              removeDeviceOrientationEvent();
175              if ('DeviceOrientationEvent' in window) {
176                  window.addEventListener('deviceorientation', handleOrientationEvent, false);
177              } else {
178                  console.log ("DeviceOrientationEvent is not supported.");
179              }
180          }
181
182          function removeDeviceOrientationEvent() {
183              if ('DeviceOrientationEvent' in window) {
184                window.removeEventListener('deviceorientation', handleOrientationEvent, false);
185              } else {
186                console.log ("DeviceOrientationEvent is not supported.");
187              }
188          }
189
190          function listenDeviceOrientationEvent2() {
191              removeDeviceOrientationEvent2();
192              if ('DeviceOrientationEvent' in window) {
193                  window.addEventListener('deviceorientationabsolute', handleOrientationEvent, false);
194              } else {
195                  console.log ("DeviceOrientationEvent is not supported.");
196              }
197          }
198
199          function removeDeviceOrientationEvent2() {
200              if ('DeviceOrientationEvent' in window) {
201                window.removeEventListener('deviceorientationabsolute', handleOrientationEvent, false);
202              } else {
203                console.log ("DeviceOrientationEvent is not supported.");
204              }
205          }
206
207          function handleOrientationEvent(event) {
208              console.log(`DeviceOrientationEvent data: ${event.timeStamp}, ${event.absolute}, ${event.alpha}, ${event.beta}, ${event.gamma}`);
209          }
210      </script>
211  </head>
212  <body>
213  <div id="dcontent" class="dcontent">
214      <h3>Motion and direction:</h3>
215      <ul class="dlist">
216          <li><button type="button" onclick="getAccelerometer()">Acceleration</button></li>;
217          <li><button type="button" onclick="getGyroscope()">Gyroscope</button></li>
218          <li><button type="button" onclick="getAbsoluteOrientationSensor()">Device orientation (absolute positioning) </button></li>;
219          <li><button type="button" onclick="listenDeviceMotionEvent()">Device motion event</button></li>;
220          <li><button type="button" onclick="listenDeviceOrientationEvent()">Device orientation event</button></li>;
221          <li><button type="button" onclick="listenDeviceOrientationEvent2()">Device orientation event (absolute positioning) </button></li>;
222      </ul>
223  </div>
224  </body>
225  </html>
226  ```
227