electron 下網頁獲取 micphone 權限

網頁獲取麥克風或攝像頭權限我們只需調用 navigator.mediaDevices.getUserMedia 方法就可喚起瀏覽器用戶授權

const useMicphone = async () => {
  try{
    let mediaStream = await navigator.mediaDevices.getUserMedia({ audio: true });
    if (mediaStream) {
      console.log('獲取 micphone 成功')
    }
  }catch(e){  
    console.warn('獲取 micphone 失敗')
  }
};

但在 electron 內可能不起作用

我們用 electron 來包裹網頁本意大多就是爲了方便獲取更多的操作權限

如果獲取失敗的話可嘗試在 electron 內提前讓用戶權限可在 electron 提供的 api 內在用戶打開軟件時提前授權

在創建窗體後,加載網頁前調用 systemPreferences.getMediaAccessStatus 授權:

import { app, systemPreferences } from "electron";

// 權限授權
async function checkMediaAccess(mediaType: 'microphone' | 'camera' | 'screen'){
  const result = systemPreferences.getMediaAccessStatus(mediaType)
  if(result !== "granted"){
    await systemPreferences.askForMediaAccess('microphone')
  }
}

// 創建主窗體
async function createMainWindow() {
  const win = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      nodeIntegration: true,
      preload: path.join(__dirname, "preload.js"),
      webSecurity: false,
    },
  });
  // 此處調用並授權
  await checkMediaAccess('microphone')

  if (isDev) {
    win.loadURL(VITE_DEV_SERVER_URL);
    win.webContents.openDevTools();
  } else {
    win.loadFile('dist/index.html')
  }
  return win;
}

如果獲取 micphone 或者攝像頭是在 electron 網頁內再嵌入的 iframe 內則還需要在 iframe 上加上 allow 屬性:

// 允許地理信息,麥克風,攝像頭.. 等權限
<iframe allow="geolocation; microphone; camera; midi; encrypted-media;" src="http://helloworld.com" style="min-width: 100%; height: 100%; width: 100%;"></iframe>

注:轉載請註明出處博客園:王二狗Sheldon池中物 ([email protected])

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章