Skip to content

getDisplayMedia with Chrome 72 throwing Not Allowed #16513

Description

@iclems
  • Output of node_modules/.bin/electron --version: v5.0.0-nightly.20190107
  • Operating System (Platform and Version): macOS Mojave 10.14.2 (18C54)
  • Output of node_modules/.bin/electron --version on last known working Electron version (if applicable): never

Expected Behavior
Using navigator.mediaDevices.getDisplayMedia({ video: true }), a native screen picker should appear.

Actual behavior
The following error is thrown: NotAllowedError: Permission denied

Screenshots
Expected dialog
image

Activity

  1. codebytere commented on Jan 23, 2019

    @codebytere
    Member

    @iclems this is probably related to: #16508

  2. MarshallOfSound commented on Jan 31, 2019

    @MarshallOfSound
    Member

    Using navigator.mediaDevices.getDisplayMedia({ video: true }), a native screen picker should appear.

    This behavior isn't expected for Electron's case. If we were to implement the plumbing required for this to work we would implement it similar to select-bluetooth-device where we emit all possible options and then the app is responsible for the "choosing" part, whether that is through a UI or just choosing a specific device by default 🤷‍♂️

  3. iclems commented on Jan 31, 2019

    @iclems
    Author

    Interesting. I understand the previous perspective on this feature but it is now part of the WebRTC standards and no longer a Chrome-specific capability implemented through extensions. It sounds strange to have an official W3C "stable" API that needs to be rebuilt via private SDKs. Certainly makes sense in the short-term, but I would assume the long-term path should be: the official API works, but developers can build a custom UI instead if they like?

  4. iclems commented on Feb 15, 2019

    @iclems
    Author

    FYI even with 5.0.0-beta.3 which includes the fix this is still not working throwing NotAllowedError: Permission denied.

  5. codebytere commented on Feb 15, 2019

    @codebytere
    Member

    @brenca ☝️

  6. iclems commented on Mar 7, 2019

    @iclems
    Author

    @brenca @sofianguy @codebytere could you reopen and make sure this isn't marked as fixed in the release notes as I just tested again in beta 5 and it is still throwing NotAllowedError: Permission denied. I'm happy to help fix it but I'm not an expert in the native binding behind it

  7. MarshallOfSound commented on Mar 7, 2019

    @MarshallOfSound
    Member

    Haven't confirmed but re-opening, @brenca can you double check this? Feel free to close again if the fix has indeed been applied successfully

  8. 16 remaining items

  9. MurzNN commented on Mar 15, 2020

    @MurzNN

    So that #16763 PR not fix this issue?

  10. saghul commented on Mar 15, 2020

    @saghul
    Contributor

    No.

  11. WesselKroos commented on Mar 21, 2020

    @WesselKroos

    I was able to polyfill getDisplayMedia using the desktopCapturer so that I can use the same code in Electron and the Chrome browser. I've only tested it in Windows 10.
    If it's handy I can wrap it in a npm package with some options to make the implementation easier.

    Adding the polyfill to a BrowserWindow

    If you want to add the polyfill to a BrowserWindow with an external website or file in it you need to preload it in the session to make it available to the website. You also need to give the BrowserWindow the permission to use the screen. We just allow everything to make it easier by implementing both setPermissionCheckHandler and setPermissionRequestHandler in it's basic form.

    main.js

    const { BrowserWindow } = require('electron')
    
    const win = new BrowserWindow({ width: 800, height: 600 })
    win.webContents.session.setPreloads([path.join(__dirname, 'preload-get-display-media-polyfill.js')])
    win.webContents.session.setPermissionCheckHandler(async (webContents, permission, details) => {
      return true
    })
    win.webContents.session.setPermissionRequestHandler(async (webContents, permission, callback, details) => {
      callback(true)
    })
    win.loadURL('https://example.com')

    The polyfill

    The polyfill overrides the native mediaDevices.getDisplayMedia implementation. The getDisplayMedia override gets the sources from the desktopCapturer and displays them in a list in the body tag. (You can use the <style> tag at the bottom of this post to style it like an overlay.)
    The user can click on a source and then the getDisplayMedia promise resolves the source.

    preload-get-display-media-polyfill.js

    const { desktopCapturer } = require('electron')
    window.navigator.mediaDevices.getDisplayMedia = () => {
      return new Promise(async (resolve, reject) => {
        try {
          const sources = await desktopCapturer.getSources({ types: ['screen', 'window'] })
    
          const selectionElem = document.createElement('div')
          selectionElem.classList = 'desktop-capturer-selection'
          selectionElem.innerHTML = `
            <div class="desktop-capturer-selection__scroller">
              <ul class="desktop-capturer-selection__list">
                ${sources.map(({id, name, thumbnail, display_id, appIcon}) => `
                  <li class="desktop-capturer-selection__item">
                    <button class="desktop-capturer-selection__btn" data-id="${id}" title="${name}">
                      <img class="desktop-capturer-selection__thumbnail" src="${thumbnail.toDataURL()}" />
                      <span class="desktop-capturer-selection__name">${name}</span>
                    </button>
                  </li>
                `).join('')}
              </ul>
            </div>
          `
          document.body.appendChild(selectionElem)
    
          document.querySelectorAll('.desktop-capturer-selection__btn')
            .forEach(button => {
              button.addEventListener('click', async () => {
                try {
                  const id = button.getAttribute('data-id')
                  const source = sources.find(source => source.id === id)
                  if(!source) {
                    throw new Error(`Source with id ${id} does not exist`)
                  }
                  
                  const stream = await window.navigator.mediaDevices.getUserMedia({
                    audio: false,
                    video: {
                      mandatory: {
                        chromeMediaSource: 'desktop',
                        chromeMediaSourceId: source.id
                      }
                    }
                  })
                  resolve(stream)
    
                  selectionElem.remove()
                } catch (err) {
                  console.error('Error selecting desktop capture source:', err)
                  reject(err)
                }
              })
            })
        } catch (err) {
          console.error('Error displaying desktop capture sources:', err)
          reject(err)
        }
      })
    }

    Some basic styling for the source selection overlay

    If you want to quickly test the polyfill here is some basic styling for the selection overlay. But of course you can customize this in any direction. You can add the style tag to the innerHTML of the selectionElem object in the polyfill.

    <style>
    .desktop-capturer-selection {
      position: fixed;
      top: 0;
      left: 0;
      width: 100%;
      height: 100vh;
      background: rgba(30,30,30,.75);
      color: #fff;
      z-index: 10000000;
      display: flex;
      align-items: center;
      justify-content: center;
    }
    .desktop-capturer-selection__scroller {
      width: 100%;
      max-height: 100vh;
      overflow-y: auto;
    }
    .desktop-capturer-selection__list {
      max-width: calc(100% - 100px);
      margin: 50px;
      padding: 0;
      display: flex;
      flex-wrap: wrap;
      list-style: none;
      overflow: hidden;
      justify-content: center;
    }
    .desktop-capturer-selection__item {
      display: flex;
      margin: 4px;
    }
    .desktop-capturer-selection__btn {
      display: flex;
      flex-direction: column;
      align-items: stretch;
      width: 145px;
      margin: 0;
      border: 0;
      border-radius: 3px;
      padding: 4px;
      background: #252626;
      text-align: left;
      transition: background-color .15s, box-shadow .15s;
    }
    .desktop-capturer-selection__btn:hover,
    .desktop-capturer-selection__btn:focus {
      background: rgba(98,100,167,.8);
    }
    .desktop-capturer-selection__thumbnail {
      width: 100%;
      height: 81px;
      object-fit: cover;
    }
    .desktop-capturer-selection__name {
      margin: 6px 0 6px;
      white-space: nowrap;
      text-overflow: ellipsis;
      overflow: hidden;
    }
    </style>
  12. codyherzog-zz commented on Apr 2, 2020

    @codyherzog-zz

    @WesselKroos

    Awesome! Thanks so much.

  13. pawhtiobo commented on May 25, 2020

    @pawhtiobo

    For a noob like me, how do I make those changes that @WesselKroos sugests?

    ty

  14. CapOM commented on Jun 8, 2020

    @CapOM
    Contributor
  15. MeirionHughes commented on Jun 30, 2020

    @MeirionHughes

    @WesselKroos kudos. I had to butcher your code to inject it into 3rd party iframe... but I got it working. Cheers.

  16. mehulpangtey commented on Jul 28, 2020

    @mehulpangtey

    @WesselKroos I think you should wrap it in an npm package.

  17. tanphamanhh commented on Aug 17, 2020

    @tanphamanhh

    in electron 9.2.0, I'm using desktopCapture.getSource(..) to get desktop source, but when I'm using it on my video conferencing application, the other participent voice is recorded to screen sharing audio too (chrome 84 does not). I'm currently stuck with how can I remove that voices from screen audio stream.

    const constraints = {
        audio: arg.audio //boolean audio or not
            ? {
                    mandatory: {
                        chromeMediaSource: 'desktop',
                    }
              }
            : false,
        video: {
            mandatory: {
                chromeMediaSource: 'desktop',
                chromeMediaSourceId: arg.sourceId //source id from select window before
            }
        }
    };
    //navigator.mediaDevices.getDisplayMedia
    navigator.mediaDevices
        .getUserMedia(constraints)
        .then((stream) => {
            console.log(stream.getAudioTracks());
            ElectronCaptureMedia.pendingSelectSourceHandle.success(stream);
        })
        .catch((err) => {
            console.log(err);
            ElectronCaptureMedia.pendingSelectSourceHandle.error(err);
        });
    
  18. jsheffers commented on Apr 8, 2021

    @jsheffers

    Has anyone successfully used the polyfill mentioned above with contextIsolation enabled? I don't think this is possible because you have to pass it through the contextBridge which doesn't seem to be allowing the stream through. Does anyone have a workaround for this?

  19. self-assigned this
    on Mar 9, 2022
  20. ruolunhui commented on Apr 1, 2022

    @ruolunhui
  21. diamond-darrell commented on Jul 24, 2022

    @diamond-darrell

    Has anyone successfully used the polyfill mentioned above with contextIsolation enabled? I don't think this is possible because you have to pass it through the contextBridge which doesn't seem to be allowing the stream through. Does anyone have a workaround for this?

    hey, regarding contextBridge and not allowing streams, is there any reference in the electron docs about it? I've run into the same problem upon upgrading my electron app and am trying to resolve it.

    Following https://www.electronjs.org/docs/latest/api/desktop-capturer I get TypeError: Failed to set the 'srcObject' property on 'HTMLMediaElement': The provided value is not of type 'MediaStream'. error instead of not allowed, which is something I guess

    upd: I managed to solve (bypass?) this issue by not returning a media stream from my render but returning a source id and requesting user media on the web app side instead. Probably it’s the intended behavior right now, dunno, hopefully this info will help someone

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions