【问题标题】:capture screen with electron when rendering a web site渲染网站时使用电子捕获屏幕
【发布时间】:2021-07-26 05:48:34
【问题描述】:

我有一个在互联网上加载网页的电子应用程序。 该网站的主要功能之一是捕获屏幕的能力,它使用

navigator.mediaDevices.getDisplayMedia({video: true});

但很明显,电子将通过 Permission denied 因为不会弹出“选择捕获窗口”来授予它任何权限。

我已经查看了一些文章并看到了desktopCapture

问题是,这是通过网页 javascript 而不是我的应用程序代码运行的,所以我不知道如何影响它。

那么我应该怎么做才能在这种情况下捕获屏幕呢?

【问题讨论】:

  • 您可以访问网页的源代码吗?你能改变它吗?如果是,这很容易使用desktopCapture
  • @aabuhijleh 不幸的是,不;我可以访问电子,我能做的最多就是通过'preload.js'等操作网页代码
  • 我已经留下了一个答案,解释了即使您没有任何访问权限也可以做到这一点
  • @aabuhijleh 是的,我看到了,今天晚些时候或几天后,我会测试它,感谢所有的努力。

标签: electron screen-capture


【解决方案1】:

您可以覆盖navigator.mediaDevices.getDisplayMedia 来调用Electron 的desktopCapturer API,如下所示。此实现假设您启用了contextIsolation,这是 Electron >= 12 中的默认行为

// preload.js

const { desktopCapturer, contextBridge } = require("electron");
const { readFileSync } = require("fs");
const { join } = require("path");

// inject renderer.js into the web page
window.addEventListener("DOMContentLoaded", () => {
  const rendererScript = document.createElement("script");
  rendererScript.text = readFileSync(join(__dirname, "renderer.js"), "utf8");
  document.body.appendChild(rendererScript);
});

contextBridge.exposeInMainWorld("myCustomGetDisplayMedia", async () => {
  const sources = await desktopCapturer.getSources({
    types: ["window", "screen"],
  });

  // you should create some kind of UI to prompt the user
  // to select the correct source like Google Chrome does
  const selectedSource = sources[0]; // this is just for testing purposes

  return selectedSource;
});

// renderer.js

navigator.mediaDevices.getDisplayMedia = async () => {
  const selectedSource = await globalThis.myCustomGetDisplayMedia();

  // create MediaStream
  const stream = await navigator.mediaDevices.getUserMedia({
    audio: false,
    video: {
      mandatory: {
        chromeMediaSource: "desktop",
        chromeMediaSourceId: selectedSource.id,
        minWidth: 1280,
        maxWidth: 1280,
        minHeight: 720,
        maxHeight: 720,
      },
    },
  });

  return stream;
};

现在调用此 API 时,将按预期将流返回给调用者

navigator.mediaDevices.getDisplayMedia({video: true});

I have created a GitHub repo that has a working implementation of this solution

【讨论】:

  • tnx,它有很大帮助,尤其是 github repo
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-09-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-15
相关资源
最近更新 更多