DeviceMotionEvent: requestPermission() static method

Limited availability

This feature is not Baseline because it does not work in some of the most widely-used browsers.

Experimental: This is an experimental technology
Check the Browser compatibility table carefully before using this in production.

Secure context: This feature is available only in secure contexts (HTTPS), in some or all supporting browsers.

Phương thức tĩnh requestPermission() của giao diện DeviceMotionEvent yêu cầu quyền của người dùng để truy cập dữ liệu chuyển động thiết bị từ cảm biến gia tốc kế và con quay hồi chuyển. Phương thức này yêu cầu transient activation, nghĩa là nó phải được kích hoạt bởi một sự kiện UI như nhấn nút.

Cú pháp

js
DeviceMotionEvent.requestPermission()

Tham số

Không có.

Giá trị trả về

Một Promise giải quyết với một chuỗi là "granted" hoặc "denied".

Ngoại lệ

Promise trả về sẽ bị từ chối với các ngoại lệ sau:

NotAllowedError DOMException

Trạng thái quyền là "prompt" và hàm gọi không có transient activation.

Bảo mật

Yêu cầu kích hoạt người dùng tạm thời. Người dùng phải tương tác với trang hoặc phần tử UI để tính năng này hoạt động.

Ví dụ

Yêu cầu quyền chuyển động thiết bị khi nhấn chuột

js
document.querySelector("button").addEventListener("click", async () => {
  if (typeof DeviceMotionEvent.requestPermission !== "function") {
    // The feature is not available, or does not need permission.
    return;
  }

  const permission = await DeviceMotionEvent.requestPermission();
  if (permission === "granted") {
    window.addEventListener("devicemotion", (event) => {
      console.log(`Acceleration X: ${event.acceleration.x}`);
      console.log(`Acceleration Y: ${event.acceleration.y}`);
      console.log(`Acceleration Z: ${event.acceleration.z}`);
    });
  }
});

Thông số kỹ thuật

Specification
Device Orientation and Motion
# dom-devicemotionevent-requestpermission

Tương thích trình duyệt

Xem thêm