In this guide, we'll demonstrate how to share your screen using twilio-video.js. Chrome 72+, Firefox 66+ and Safari 12.2+ support the getDisplayMedia API. This can be used to capture the screen directly from the web app. For previous versions of Chrome, you'll need to create an extension. The web application will communicate with this extension to capture the screen.
To share your screen in a Room, use getDisplayMedia()
to get the screen's MediaStreamTrack and create a LocalVideoTrack:
1const { connect, LocalVideoTrack } = require('twilio-video');23const stream = await navigator.mediaDevices.getDisplayMedia({video: {frameRate: 15}});4const screenTrack = new LocalVideoTrack(stream.getTracks()[0], {name:'myscreenshare'});
Then, you can either publish the LocalVideoTrack while joining a Room:
1const room = await connect(token, {2name: 'presentation',3tracks: [screenTrack]4});
or, publish the LocalVideoTrack after joining a Room:
1const room = await connect(token, {2name: 'presentation'3});45room.localParticipant.publishTrack(screenTrack);
To share your screen in the Room, use getUserMedia()
to get the screen's MediaStreamTrack and create a LocalVideoTrack:
1const { connect, LocalVideoTrack } = require('twilio-video');23const stream = await navigator.mediaDevices.getUserMedia({4mediaSource: 'window'5});67const screenTrack = new LocalVideoTrack(stream.getTracks()[0]);
Then, you can either publish the LocalVideoTrack while joining a Room:
1const room = await connect(token, {2name: 'presentation',3tracks: [screenTrack]4});
or, publish the LocalVideoTrack after joining a Room:
1const room = await connect(token, {2name: 'presentation'3});45room.localParticipant.publishTrack(screenTrack);
Our web app will send requests to our extension.
Since we want to enable Screen Capture, the most important message our web app can send to our extension is a request to capture the user's screen. We want to distinguish these requests from other types of messages, so we will set its type
equal to "getUserScreen". (We could choose any string for the message type
, but "getUserScreen" bears a nice resemblance to the browser's getUserMedia
API.) Also, Chrome allows us to specify the DesktopCaptureSourceTypes we would like to prompt the user for, so we should include another property, sources
, equal to an Array of DesktopCaptureSourceTypes. For example, the following "getUserScreen" request will prompt access to the user's screen, window, or tab:
1{2"type": "getUserScreen",3"sources": ["screen", "window", "tab"]4}
Our web app should expect a success or error message in response.
Our extension will respond to our web app's requests.
Any time we need to communicate a successful result from our extension, we'll send a message with type
equal to "success", and possibly some additional data. For example, if our web app's "getUserScreen" request succeeds, we should include the resulting streamId
that Chrome provides us. Assuming Chrome returns us a streamId
of "123", we should respond with
1{2"type": "success",3"streamId": "123"4}
Any time we need to communicate an error from our extension, we'll send a message with type
equal to "error" and an error message
. For example, if our web app's "getUserScreen" request fails, we should respond with
1{2"type": "error",3"message": "Failed to get stream ID"4}
In this guide, we propose the following project structure, with two top-level folders for our web app and extension.
1.2├── web-app3│ ├── index.html4│ └── web-app.js5└── extension6├── extension.js7└── manifest.json
Note: If you are adapting this guide to an existing project you may tweak the structure to your liking.
Since our web app will be loaded in a browser, we need some HTML entry-point to our application. This HTML file should load web-app.js and twilio-video.js.
Our web app's logic for creating twilio-video.js Clients, connecting to Rooms, and requesting the user's screen will live in this file.
Our extension will run extension.js in a background page. This file will be responsible for handling requests. For more information, refer to Chrome's documentation on background pages.
Every extension requires a manifest.json file. This file grants our extension access to Chrome's Tab and DesktopCapture APIs and controls which web apps can send messages to our extension. For more information on manifest.json, refer to Chrome's documentation on the manifest file format; otherwise, feel free to tweak the example provided here. Note that we've included "://localhost/" in our manifest.json's "externally_connectable" section. This is useful during development, but you may not want to publish your extension with this value. Consider removing it once you're done developing your extension.
1{2"manifest_version": 2,3"name": "your-plugin-name",4"version": "0.10",5"background": {6"scripts": ["extension.js"]7},8"externally_connectable": {9"matches": ["*://localhost/*", "*://*.example.com/*"]10},11"permissions": [12"desktopCapture",13"tabs"14]15}
We define a helper function in our web app, getUserScreen
, that will send a "getUserScreen" request to our extension using Chrome's sendMessage
API. If our request succeeds, we can expect a "success" response containing a streamId
. Our response callback will pass that streamId
to getUserMedia
, and—if all goes well—our function will return a Promise that resolves to a MediaStream representing the user's screen.
1/**2* Get a MediaStream containing a MediaStreamTrack that represents the user's3* screen.4*5* This function sends a "getUserScreen" request to our Chrome Extension which,6* if successful, responds with the sourceId of one of the specified sources. We7* then use the sourceId to call getUserMedia.8*9* @param {Array<DesktopCaptureSourceType>} sources10* @param {string} extensionId11* @returns {Promise<MediaStream>} stream12*/13function getUserScreen(sources, extensionId) {14const request = {15type: 'getUserScreen',16sources: sources17};18return new Promise((resolve, reject) => {19chrome.runtime.sendMessage(extensionId, request, response => {20switch (response && response.type) {21case 'success':22resolve(response.streamId);23break;2425case 'error':26reject(new Error(error.message));27break;2829default:30reject(new Error('Unknown response'));31break;32}33});34}).then(streamId => {35return navigator.mediaDevices.getUserMedia({36video: true37});38});39}
Assume for the moment that we know our extension's ID and that we want to request the user's screen, window, or tab. We have all the information we need to call getUserScreen
. When the Promise returned by getUserScreen
resolves, we need to use the resulting MediaStream to construct the LocalVideoTrack object we intend to use in our Room. Once we've constructed our LocalVideoTrack representing the user's screen, we have two options for publishing it to the Room:
connect
, orpublishTrack
.Finally, we'll also want to add a listener for the "stopped" event. If the user stops sharing their screen, the "stopped" event will fire, and we may want to remove the LocalVideoTrack from the Room. We can do this by calling unpublishTrack
.
1const { connect, LocalVideoTrack } = require('twilio-video');23// Option 1. Provide the screenLocalTrack when connecting.4async function option1() {5const stream = await getUserScreen(['window', 'screen', 'tab'], 'your-extension-id');6const screenLocalTrack = new LocalVideoTrack(stream.getVideoTracks()[0]);78const room = await connect('my-token', {9name: 'my-room-name',10tracks: [screenLocalTrack]11});1213screenLocalTrack.once('stopped', () => {14room.localParticipant.unpublishTrack(screenLocalTrack);15});1617return room;18}1920// Option 2. First connect, and then publish screenLocalTrack.21async function option2() {22const room = await connect('my-token', {23name: 'my-room-name',24tracks: []25});2627const stream = await getUserScreen(['window', 'screen', 'tab'], 'your-extension-id');28const screenLocalTrack = new LocalVideoTrack(stream.getVideoTracks()[0]);2930screenLocalTrack.once('stopped', () => {31room.localParticipant.unpublishTrack(screenLocalTrack);32});3334await room.localParticipant.publishTrack(screenLocalTrack);35return room;36}
Our extension will listen to Chrome's onMessageExternal
event, which will be fired whenever our web app sends a message to the extension. In the event listener, we switch on the message type
in order to determine how to handle the request. In this example, we only care about "getUserScreen" requests, but we also include a default
case for handling unrecognized responses.
1chrome.runtime.onMessageExternal.addListener((message, sender, sendResponse) => {2switch (message && message.type) {3// Our web app sent us a "getUserScreen" request.4case 'getUserScreen':5handleGetUserScreenRequest(message.sources, sender.tab, sendResponse);6break;78// Our web app sent us a request we don't recognize.9default:10handleUnrecognizedRequest(sendResponse);11break;12}1314return true;15});
We define a helper function in our extension, handleGetUserScreenRequest
, for responding to "getUserScreen" requests. The function invokes Chrome's chooseDesktopMedia
API with sources
and, if the request succeeds, sends a success response containing a streamId
; otherwise, it sends an error response.
1/**2* Respond to a "getUserScreen" request.3* @param {Array<DesktopCaptureSourceType>} sources4* @param {Tab} tab5* @param {function} sendResponse6* @returns {void}7*/8function handleGetUserScreenRequest(sources, tab, sendResponse) {9chrome.desktopCapture.chooseDesktopMedia(sources, tab, streamId => {10// The user canceled our request.11if (!streamId) {12sendResponse({13type: 'error',14message: 'Failed to get stream ID'15});16}1718// The user accepted our request.19sendResponse({20type: 'success',21streamId: streamId22});23});24}
For completeness, we'll also handle unrecognized requests. Any time we receive a message with a type
we don't understand (or lacking a type
altogether), our extension's handleUnrecognizedResponse
function will send the following error response:
1{2"type": "error",3"message": "Unrecognized request"4}
handleUnrecognizedRequest Implementation
1/**2* Respond to an unrecognized request.3* @param {function} sendResponse4* @returns {void}5*/6function handleUnrecognizedRequest(sendResponse) {7sendResponse({8type: 'error',9message: 'Unrecognized request'10});11}
Finally, once we've built and tested our web app and extension, we will want to publish our extension in the Chrome Web Store so that users of our web app can enjoy our new Screen Capture functionality. Take a look at Chrome's documentation for more information.