Electron 中查询和申请设备权限

Electron 中查询和申请设备权限

本文详细介绍了 Electron 项目中不同操作系统如何实现摄像头、麦克风、屏幕权限的查询和申请。

Electron 相关 API 介绍

js 复制代码
- mediaType: string
    - microphone      
    - camera          
    - screen          
- return: string 
    - not-determined
    - granted
    - denied
    - restricted
    - unkonwn
js 复制代码
- mediaType: string
    - microphone    
    - camera        
- return: Promise,传递一个无效的 mediaType 时 Promise 的状态也为 rejected。

注意: askForMediaAccess 方法的弹窗提醒只会出现一次,第一次出现拒绝授权后,以后必须要在系统首选项面板中更改权限后重新启动才能使权限生效。

不同操作系统 API 支持情况

macOS Windows Linux
getMediaAccessStatus
askForMediaAccess

权限查询、申请示例代码

js 复制代码
// main.js

const execCommond = require("child_process").exec;

/**
 * @param {String} device 'microphone' | 'camera'
 */
async function checkAndApplyDevicesAccessPrivilege(device) {
  if (process.platform === "linux") return;
  const promptText = {
    camera: "当前应用无摄像头权限,请授权后重新启动应用。",
    microphone: "当前应用无麦克风权限,请授权后重新启动应用。",
  };
  const devicePrivilege = systemPreferences.getMediaAccessStatus(device);
  if (devicePrivilege !== "granted") {
    if (process.platform === "darwin") {
      try {
        const isAuthorization = await systemPreferences.askForMediaAccess(device);
        if (!isAuthorization) {
          console.log(promptText[device]);
        }
      } catch (error) {
        console.log(promptText[device]);
      }
    } else {
      console.log(promptText[device]);
    }
  }
}


function checkAndApplyScreenShareAccessPrivilege() {
  if (process.platform === "linux") return;
  const screenPrivilege = systemPreferences.getMediaAccessStatus("screen");
  if (screenPrivilege !== "granted") {
    if (process.platform === "darwin") {
      console.log('当前应用无屏幕捕获权限,即将跳转至授权页面,请授权后重新启动应用。')
      execCommond(`open x-apple.systempreferences:com.apple.preference.security?Privacy_ScreenCapture`);
    }
}

使用案例:

js 复制代码
// main.js
...
app.whenReady().then(async () =>{
    createWindow()
    await checkAndApplyDevicesAccessPrivilege("camera");
    await checkAndApplyDevicesAccessPrivilege("microphone");
    checkAndApplyScreenShareAccessPrivilege();
})
...

其他问题

检测出无权限后想要弹窗提示怎么做?

通过 Electron 的主进程模块 dialog 可以实现系统级的弹窗提示,详细介绍见官网。

使用案例:

js 复制代码
// main.js
const { dialog } = require("electron");

dialog.showMessageBoxSync(browserWindow, {
        message:'提示消息',
        type: "warning",
});

检测出无权限后想跳转至权限设置窗口如何实现?

通过 Node.js 子进程 child_process 的 exec 模块执行命令行实现窗口跳转,详细介绍见官网。

使用案例:

js 复制代码
// main.js

const execCommond = require("child_process").exec;



/**
 * @param {String} device 'microphone' | 'camera'
 */
function jumpToPrivilegeSettings(device) {
  if ((device !== "camera" && device !== "microphone") || process.platform === "linux") return;
  const privacyTypeObjOfMac = {
    camera: "Privacy_Camera",
    microphone: "Privacy_Microphone",
  };
  const privacyTypeObjOfWindows = {
    camera: "privacy-webcam",
    microphone: "privacy-microphone",
  };
  if (process.platform === "darwin") {
    execCommond(`open x-apple.systempreferences:com.apple.preference.security?${privacyTypeObjOfMac[device]}`);
  } else {
    execCommond(`start ms-settings:${privacyTypeObjOfWindows[device]}`);
  }
}

... 
    // 检测到无麦克风权限后
   jumpToPrivilegeSettings('microphone')   
...
相关推荐
逸铭1 天前
Day 2:10 分钟搭 Electron + Vite + Vue 3——AnchorChat 的第一个窗口
electron·客户端
阿里云云原生2 天前
破局 Electron 监控盲区:基于 WASM 与 IPC 桥接的零侵入可观测 SDK 设计
electron
TrisighT3 天前
Electron 跑在鸿蒙 PC 上,单窗口和多窗口内存差 800MB?我抓了 5 组数据
性能优化·electron·harmonyos
怕浪猫7 天前
Electron 开发实战(十六):总结与展望|生态现状、框架对比、行业趋势与学习指南
前端·javascript·electron
古德new8 天前
鸿蒙PC使用electron迁移:Joplin Electron 桌面适配全记录
华为·electron·harmonyos
三声三视8 天前
Electron 在鸿蒙 PC 上跑 webview,我是怎么把首屏从 4.2s 干到 1.1s 的
华为·electron·harmonyos·鸿蒙
「、皓子~8 天前
海狸IM 2.0 正式发布:六端齐发,开源 IM 迈入新阶段
flutter·electron·开源软件·ai编程·交友·im
JOJO数据科学9 天前
JupyterLab Electron 鸿蒙 PC 适配全记录:从 Python 原生崩溃到 node-static 本地工作台
python·electron·harmonyos
悟空瞎说9 天前
深度排查:Electron MAS 包播放 HDR 视频引发界面卡死问题全解析
electron
不良使9 天前
鸿蒙PC迁移:使用Electron`logseq-master-ohos` 鸿蒙适配全记录
jvm·electron·harmonyos