Skip to contentSkip to navigationSkip to topbar
On this page

Screen Capture - JavaScript


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(link takes you to an external page) 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(link takes you to an external page). The web application will communicate with this extension to capture the screen.


Chrome (72+), Firefox (66+), Safari (12.2+): Use getDisplayMedia

chrome-72-firefox-66-safari-122-use-getdisplaymedia page anchor

To share your screen in a Room, use getDisplayMedia() to get the screen's MediaStreamTrack and create a LocalVideoTrack(link takes you to an external page):

1
const { connect, LocalVideoTrack } = require('twilio-video');
2
3
const stream = await navigator.mediaDevices.getDisplayMedia({video: {frameRate: 15}});
4
const screenTrack = new LocalVideoTrack(stream.getTracks()[0], {name:'myscreenshare'});

Then, you can either publish the LocalVideoTrack while joining a Room:

1
const room = await connect(token, {
2
name: 'presentation',
3
tracks: [screenTrack]
4
});

or, publish the LocalVideoTrack after joining a Room:

1
const room = await connect(token, {
2
name: 'presentation'
3
});
4
5
room.localParticipant.publishTrack(screenTrack);

Firefox (65-): Use getUserMedia

firefox-65--use-getusermedia page anchor

To share your screen in the Room, use getUserMedia() to get the screen's MediaStreamTrack and create a LocalVideoTrack(link takes you to an external page):

1
const { connect, LocalVideoTrack } = require('twilio-video');
2
3
const stream = await navigator.mediaDevices.getUserMedia({
4
mediaSource: 'window'
5
});
6
7
const screenTrack = new LocalVideoTrack(stream.getTracks()[0]);

Then, you can either publish the LocalVideoTrack while joining a Room:

1
const room = await connect(token, {
2
name: 'presentation',
3
tracks: [screenTrack]
4
});

or, publish the LocalVideoTrack after joining a Room:

1
const room = await connect(token, {
2
name: 'presentation'
3
});
4
5
room.localParticipant.publishTrack(screenTrack);

Screen Share Not Supported on Mobile Web Browsers

screen-share-not-supported-on-mobile-web-browsers page anchor

Currently, we do not support Screen Sharing on Mobile Browsers as getDisplayMedia(link takes you to an external page) is not supported. However, it can be achieved through the iOS SDK and Android SDK.


Chrome (71-): Build a Screen Share Extension

chrome-71--build-a-screen-share-extension page anchor

Our web app and extension will communicate using message passing(link takes you to an external page). Specifically, our web app will be responsible for sending requests to our extension using Chrome's sendMessage(link takes you to an external page) API, and our extension will be responsible for responding to requests raised through Chrome's onMessageExternal(link takes you to an external page) event. By convention, every message passed between our web app and extension will be a JSON object containing a type property, and we will use this type property to distinguish different types of messages.

Web App Requests

web-app-requests page anchor

Our web app will send requests to our extension.

"getUserScreen" Requests

getuserscreen-requests page anchor

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(link takes you to an external page) API.) Also, Chrome allows us to specify the DesktopCaptureSourceType(link takes you to an external page)s 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-app
3
├── index.html
4
└── web-app.js
5
└── extension
6
├── extension.js
7
└── 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(link takes you to an external page).

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(link takes you to an external page); 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(link takes you to an external page) API. If our request succeeds, we can expect a "success" response containing a streamId. Our response callback will pass that streamId to getUserMedia(link takes you to an external page), 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's
3
* 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. We
7
* then use the sourceId to call getUserMedia.
8
*
9
* @param {Array<DesktopCaptureSourceType>} sources
10
* @param {string} extensionId
11
* @returns {Promise<MediaStream>} stream
12
*/
13
function getUserScreen(sources, extensionId) {
14
const request = {
15
type: 'getUserScreen',
16
sources: sources
17
};
18
return new Promise((resolve, reject) => {
19
chrome.runtime.sendMessage(extensionId, request, response => {
20
switch (response && response.type) {
21
case 'success':
22
resolve(response.streamId);
23
break;
24
25
case 'error':
26
reject(new Error(error.message));
27
break;
28
29
default:
30
reject(new Error('Unknown response'));
31
break;
32
}
33
});
34
}).then(streamId => {
35
return navigator.mediaDevices.getUserMedia({
36
video: true
37
});
38
});
39
}

Connecting to a Room with Screen Sharing

connecting-to-a-room-with-screen-sharing page anchor

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:

  1. We can provide it in our call to connect, or
  2. We can publish it after connecting to the Room using publishTrack.

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.

1
const { connect, LocalVideoTrack } = require('twilio-video');
2
3
// Option 1. Provide the screenLocalTrack when connecting.
4
async function option1() {
5
const stream = await getUserScreen(['window', 'screen', 'tab'], 'your-extension-id');
6
const screenLocalTrack = new LocalVideoTrack(stream.getVideoTracks()[0]);
7
8
const room = await connect('my-token', {
9
name: 'my-room-name',
10
tracks: [screenLocalTrack]
11
});
12
13
screenLocalTrack.once('stopped', () => {
14
room.localParticipant.unpublishTrack(screenLocalTrack);
15
});
16
17
return room;
18
}
19
20
// Option 2. First connect, and then publish screenLocalTrack.
21
async function option2() {
22
const room = await connect('my-token', {
23
name: 'my-room-name',
24
tracks: []
25
});
26
27
const stream = await getUserScreen(['window', 'screen', 'tab'], 'your-extension-id');
28
const screenLocalTrack = new LocalVideoTrack(stream.getVideoTracks()[0]);
29
30
screenLocalTrack.once('stopped', () => {
31
room.localParticipant.unpublishTrack(screenLocalTrack);
32
});
33
34
await room.localParticipant.publishTrack(screenLocalTrack);
35
return room;
36
}

Our extension will listen to Chrome's onMessageExternal(link takes you to an external page) 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.

1
chrome.runtime.onMessageExternal.addListener((message, sender, sendResponse) => {
2
switch (message && message.type) {
3
// Our web app sent us a "getUserScreen" request.
4
case 'getUserScreen':
5
handleGetUserScreenRequest(message.sources, sender.tab, sendResponse);
6
break;
7
8
// Our web app sent us a request we don't recognize.
9
default:
10
handleUnrecognizedRequest(sendResponse);
11
break;
12
}
13
14
return true;
15
});

We define a helper function in our extension, handleGetUserScreenRequest, for responding to "getUserScreen" requests. The function invokes Chrome's chooseDesktopMedia(link takes you to an external page) 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>} sources
4
* @param {Tab} tab
5
* @param {function} sendResponse
6
* @returns {void}
7
*/
8
function handleGetUserScreenRequest(sources, tab, sendResponse) {
9
chrome.desktopCapture.chooseDesktopMedia(sources, tab, streamId => {
10
// The user canceled our request.
11
if (!streamId) {
12
sendResponse({
13
type: 'error',
14
message: 'Failed to get stream ID'
15
});
16
}
17
18
// The user accepted our request.
19
sendResponse({
20
type: 'success',
21
streamId: streamId
22
});
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} sendResponse
4
* @returns {void}
5
*/
6
function handleUnrecognizedRequest(sendResponse) {
7
sendResponse({
8
type: 'error',
9
message: 'Unrecognized request'
10
});
11
}

Publishing the Extension

publishing-the-extension page anchor

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(link takes you to an external page) for more information.

Need some help?

Terms of service

Copyright © 2024 Twilio Inc.