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')   
...
相关推荐
又过二十6 小时前
用 Electron 做的 AI 视频切片工作台:VClip 的技术选型与踩坑实录
ai·electron·aigc·funasr·视频切片
不可能片场2 天前
工程实践 日志文件名是北京日期 内容却是 UTC
前端·electron
不可能片场6 天前
工程实践 台账备份从全量复制改成增量日志
前端·electron
林恒smileZAZ6 天前
用 Vue 3 + Electron 做桌宠:从启动退出到拖拽、单击与鼠标穿透
vue.js·electron·计算机外设
非常好吃的糖6 天前
Windows 桌面端的语音唤醒:从「识别出文字」到「识别出唤醒词」
electron
Suprman8 天前
从 B/S 到 Electron:平面排版套料系统桌面版开发实战
javascript·平面·electron·排序算法
不可能片场10 天前
工程实践 一个缓存把选片从十分钟压到一分钟
前端·electron
lemon_sjdk11 天前
从一段真实的 Electron IM 前端代码,看高级前端的工程化修养
前端·electron·状态模式·im
优选资源分享11 天前
PicGo v3.0.3 新版 | 开源免费图床工具
javascript·笔记·electron
不可能片场11 天前
Electron 发布核验 别把没查到当成没发出去
前端·electron