33

I'm currently writing a chrome extension which uses Chrome's DesktopCapture API. I'm struggling to set a callback when someone clicks on "Stop sharing".

Stop sharing Screenshot

I tried using the onended EventHandler of the MediaStream, but the MediaStream's ended property is still set to true after clicking on the button.

The only difference I could find between the stream (before and after clicking the button) is that the videoTracks.readyState is set to ended.

Edit: I would also like to notice if the user closes the window they were streaming before.

wpp
  • 7,093
  • 4
  • 33
  • 65

3 Answers3

65

I solved this issue by assigning an EventHandler on the videoTrack's onended property:

  // somebody clicked on "Stop sharing"
  stream.getVideoTracks()[0].onended = function () {
    // doWhatYouNeedToDo();
  };

As far as my edit goes (noticing a closing window): it also fires the event.

wpp
  • 7,093
  • 4
  • 33
  • 65
  • Hey, I appreciate you putting this information here. I am having an issue with the desktopCapture over RTCPeerConnection. Would you mind taking a look at [my question?](http://stackoverflow.com/q/26111693/1375316) – trey-jones Sep 30 '14 at 15:10
  • Is there a way I can have my own stop sharing button in application and avoid using this chrome bar/ tray? If yes, please let me know how can I hide it completely? – user2801184 Dec 14 '15 at 23:53
  • @user2801184 You can have a custom stop sharing button. But I don't think you can avoid having the chrome bar/tray. You could ask/report on webrtc mailing list though. – wpp Dec 15 '15 at 09:24
  • @wpp I wrote a custom button and used shareStream.getVideoTracks()[0].stop(); I will report it to webrtc mail. Can you please answer this question if its possible? http://stackoverflow.com/questions/34235155/chrome-webrtc-screen-sharing-minimizing-and-maximizing-screen-shows-black-scree – user2801184 Dec 15 '15 at 21:58
  • @wpp I am using video js. Where do I put these codes.? – Maneesh Rao May 07 '21 at 06:01
  • This works in screen share, window share scenarios. But not in tab share scenarios. – Tamil Vendhan Kanagarasu Jul 01 '22 at 10:36
13

Now we have oninactive, You can use like this

stream.oninactive = () => {}
Diego Gurgel
  • 166
  • 2
  • 8
2
stream.onended = () => { // Click on browser UI stop sharing button
  console.info("Recording has ended");
};

Where to get stream? Using adapter.js (making universal Promise based API across browsers):

navigator.mediaDevices.getUserMedia(..).then((stream) => {..});
lukyer
  • 7,595
  • 3
  • 37
  • 31