调用浏览器的震动硬件调用

背景

近来在做一个PC肌训练工具,需要用到声光震动来提醒用户做出相应的动作。

这里记录网页调用震动功能的代码实现,需要特别注意的是,小米等手机厂商自带很严格的隐私权限审查,会自动拒绝浏览器非白名单网址的震动请求,需要用户自行允许 特定网址的震动权限请求。

技术

概述

网页震动功能基于 **Vibration API** 实现,允许开发者通过JavaScript控制设备振动硬件。该API主要应用于增强用户交互体验,常见于移动端网页游戏、通知提醒等场景。

基本使用

// 单次震动(单位:毫秒)
navigator.vibrate(200);

// 模式震动(交替震动/暂停)
navigator.vibrate([100, 50, 200]);

// 立即停止所有震动
navigator.vibrate(0);  

使用场景

  • 游戏反馈(碰撞、得分等)
  • 表单验证失败提示
  • 重要通知提醒
  • 无障碍交互辅助

兼容性支持

浏览器支持版本备注
Chrome32+ (Android)桌面端不支持
Firefox11+支持桌面版(需硬件)
Safari❌ 不支持iOS全系不支持
Edge79+仅限Android版本

案例

本案例在小米浏览器下,需要设置允许浏览器特定网址调用震动权限,在微信中则不需要,直接可以调用震动。

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>测试手机震动功能</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            text-align: center;
            margin-top: 50px;
        }
        button {
            padding: 10px 20px;
            font-size: 16px;
            margin: 10px;
            cursor: pointer;
        }
        .warning {
            color: red;
            font-weight: bold;
            margin-top: 20px;
        }
    </style>
</head>
<body>
    <h1>测试手机震动功能</h1>
    <p>点击按钮测试震动功能。</p>

    <button onclick="vibrateShort()">短震动(200ms)</button>
    <button onclick="vibrateLong()">长震动(500ms)</button>
    <button onclick="vibratePattern()">自定义震动模式</button>

    <div id="warning" class="warning">如何没有响应请转去微信里面打开</div>

    <script>
        // 检测浏览器是否支持 Vibration API
        const isVibrationSupported = 'vibrate' in navigator;

        // 如果不支持,显示警告信息
        if (!isVibrationSupported) {
            document.getElementById('warning').innerText = '您的浏览器不支持震动功能,请尝试使用微信小程序。';
        }

        // 短震动(200ms)
        function vibrateShort() {
            if (isVibrationSupported) {
                navigator.vibrate(200);
                //alert("短震动已触发!");
            } else {
                alert("您的浏览器不支持震动功能。");
            }
        }

        // 长震动(500ms)
        function vibrateLong() {
            if (isVibrationSupported) {
                navigator.vibrate(500);
                //alert("长震动已触发!");
            } else {
                alert("您的浏览器不支持震动功能。");
            }
        }

        // 自定义震动模式
        function vibratePattern() {
            if (isVibrationSupported) {
                // 震动 200ms,暂停 100ms,震动 300ms
                navigator.vibrate([200, 100, 300, 200, 400]);
                //alert("自定义震动模式已触发!");
            } else {
                alert("您的浏览器不支持震动功能。");
            }
        }
    </script>
</body>
</html>

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注

Scroll to Top