今天接續昨天的 WebRTC , 我們將做成 Electron 的版本 ,
而且將攝像頭的使用改成用擷取螢幕訊息作替代
成果圖

修改 window.navigator.mediaDevices.getUserMedia 的 stream 來源
將昨天 html 的部分中的 async createMedia 方法 , 改成用指定 sourceId 的形式取得 localstream
async createMedia() {
+  const desktopCapture = async (sourceId) => {
+
+    constraints = {
+            audio: false,
+            video: {
+                mandatory: {
+                    chromeMediaSource: 'desktop',
+                    chromeMediaSourceId: sourceId,
+                    minWidth: 1280,
+                    maxWidth: 1280,
+                    minHeight: 720,
+                    maxHeight: 720
+                }
+            }
+        };
+
+        return await navigator.mediaDevices.getUserMedia(constraints);
+    };
    
    // 儲存本地流到全域
+    this.localstream = await desktopCapture(this.sourceId);
-    this.localstream = await window.navigator.mediaDevices.getUserMedia({ audio: true, video: true })
    this.$refs.myVideo.srcObject = this.localstream;
},
在 main.js 中追加兩個 ipcMain channel - pick-sourceId . mounted-webRTC-html
// add below in main.js
ipcMain.on('pick-sourceId', (event, sourceId) => {
    electronSourceId = sourceId;
    win.loadFile('webrtc-electron.html');
});
ipcMain.on('mounted-webRTC-html', (event) => {
    event.reply('setting-sourceId', electronSourceId);
});
要用到 mounted-webRTC-html 這個 channel 那 html 的部分要追加 mounted
// 將 main Process 中的 sourceId 載入到 Vue 中
mounted() {
    ipcRenderer.on('setting-sourceId', (event, sourceId) => this.sourceId = sourceId);
    ipcRenderer.send('mounted-webRTC-html');
},
當然我們需要準備選擇 sourceId 用到的 HTML - select-source.html
接著 createWindow 載入 select-source.html
 mainWindow.loadFile('select-source.html');
我們就有分享桌面訊息的 Electron 應用程式了 !

今年小弟第一次參加 `鐵人賽` , 如文章有誤 , 請各位前輩提出指正 , 感謝  <(_ _)>