To use a fake video file from your computer instead of a fake desktop capture stream in Playwright, you can use the path option in the page.addScriptTag() method to inject a script into the page that creates a new <video> element and sets its src attribute to the path of your video file.
Here's an example of how you can do this:
const { chromium } = require('playwright');
const path = require('path');
(async () => {
const browser = await chromium.launch();
const context = await browser.newContext();
// Get the path of your fake video file
const videoPath = path.join(__dirname, 'fake-video.mp4');
// Pass the fake video file path to the browser
const page = await context.newPage();
await page.goto('https://example.com');
await page.addScriptTag({
path: videoPath
});
await page.evaluate(() => {
const video = document.createElement('video');
video.src = 'fake-video.mp4';
document.body.appendChild(video);
video.play();
});
// Close the browser
await browser.close();
})();
User
I think this is quite back idea to do it this way. Can you tell me another way?
Assistant
Sure! Another way to use a fake video file from your computer in Playwright is to use the page.setContent() method to set the HTML content of the page to a <video> element with the src attribute set to the path of your video file.
Here's an example of how you can do this:
const { chromium } = require('playwright');
const path = require('path');
(async () => {
const browser = await chromium.launch();
const context = await browser.newContext();
// Get the path of your fake video file
const videoPath = path.join(__dirname, 'fake-video.mp4');
// Pass the fake video file path to the browser
const page = await context.newPage();
await page.setContent(`
<html>
<body>
<video id="my-video" src="${videoPath}" autoplay></video>
</body>
</html>
`);
// Close the browser
await browser.close();
})();
In this example, we first get the path of the fake video file using the path.join() method. We then use the page.setContent() method to set the HTML content of the page to a <video> element with the src attribute set to the path of our video file.
Note that in this example, we've also set the attribute on the element to start playing the video automatically. If you don't want the video to start playing automatically, you can remove this attribute.
User
I don't want to change page code.
Assistant
If you don't want to change the code of the page you're testing, you can still use a fake video file from your computer in Playwright by creating a local web server that serves the video file and injecting a script into the page that creates a new element and sets its attribute to the URL of the video file.
User
I don't want to add script tag to page. I just want when page will ask for getUserMedia - that it will get video from my computer
Assistant
User
i don't want to replace getUserMedia
Assistant
If you don't want to replace the getUserMedia() method, you can intercept the navigator.mediaDevices.getUserMedia() method using the page.route() method and return a object created from your fake video file.
User
i dont want to Intercept
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
In this example, we first create a fake desktop capture stream using the navigator.mediaDevices.getUserMedia() method. We then pass this stream to the browser using the page.evaluate() method, which allows us to execute JavaScript code in the context of the page.
Inside the page.evaluate() method, we create a new <video> element, set its srcObject property to the fake desktop capture stream, and append it to the page. Finally, we call the play() method on the video element to start playing the stream.
Note that this code assumes that the page has already been loaded before the fake desktop capture stream is passed to the browser. If you need to pass the stream to the browser before the page is loaded, you may need to modify the code accordingly.
In this example, we first get the path of the fake video file using the path.join() method. We then pass this path to the page.addScriptTag() method using the path option.
Inside the page.evaluate() method, we create a new <video> element, set its src attribute to 'fake-video.mp4' (which refers to the video file we passed to the browser), append it to the page, and call the play() method on the video element to start playing the video.
Note that you'll need to replace 'fake-video.mp4' with the name of your own video file in the page.evaluate() method.
autoplay
<video>
<video>
src
Here's an example of how you can do this:
const { chromium } = require('playwright');
const path = require('path');
const http = require('http');
const fs = require('fs');
(async () => {
const browser = await chromium.launch();
const context = await browser.newContext();
// Get the path of your fake video file
const videoPath = path.join(__dirname, 'fake-video.mp4');
// Create a local web server that serves the video file
const server = http.createServer((req, res) => {
fs.readFile(videoPath, (err, data) => {
if (err) {
res.writeHead(404);
res.end(JSON.stringify(err));
return;
}
res.setHeader('Content-Type', 'video/mp4');
res.setHeader('Content-Length', data.length);
res.write(data);
res.end();
});
});
server.listen(8080, () => {
console.log('Local web server started at http://localhost:8080');
});
// Inject a script into the page that plays the fake video
const page = await context.newPage();
await page.goto('https://example.com');
await page.addScriptTag({
content: `
const video = document.createElement('video');
video.src = 'http://localhost:8080/fake-video.mp4';
document.body.appendChild(video);
video.play();
`
});
// Close the server and the browser
server.close();
await browser.close();
})();
In this example, we first get the path of the fake video file using the path.join() method. We then create a local web server that serves the video file using the http.createServer() method.
Inside the server's request handler, we read the video file from disk and send it back to the client with the appropriate headers.
Inside the page.addScriptTag() method, we inject a script into the page that creates a new <video> element, sets its src attribute to the URL of the video file on our local web server ('http://localhost:8080/fake-video.mp4'), appends it to the page, and calls the play() method on the video element to start playing the video.
Note that in this example, we've used port 8080 for the local web server, but you can use any available port. Also, you'll need to replace 'fake-video.mp4' with the name of your own video file in the page.addScriptTag() method.
If you want the page to receive the video from your computer when it requests access to the user's camera using getUserMedia(), you can use the context.grantPermissions() method to grant permission to the page to access your camera, and then use the context.exposeBinding() method to expose a custom function to the page that will return a MediaStream object created from your fake video file.
Here's an example of how you can do this:
const { chromium } = require('playwright');
const path = require('path');
const fs = require('fs');
(async () => {
const browser = await chromium.launch();
const context = await browser.newContext();
// Get the path of your fake video file
const videoPath = path.join(__dirname, 'fake-video.mp4');
// Grant permission to the page to access the camera
await context.grantPermissions(['camera']);
// Expose a custom function to the page that returns a MediaStream object
await context.exposeBinding('getFakeVideoStream', (source, page) => {
const stream = fs.createReadStream(videoPath);
const videoStream = new MediaStream();
const videoTrack = videoStream.addTrack(stream.getVideoTracks()[0]);
return Promise.resolve(videoStream);
});
// Navigate to the page that requests access to the camera
const page = await context.newPage();
await page.goto('https://example.com');
// Wait for the page to request access to the camera and replace the getUserMedia method with our custom function
await page.waitForFunction('navigator.mediaDevices.getUserMedia', { timeout: 0 });
await page.evaluate(() => {
navigator.mediaDevices.getUserMedia = async function(constraints) {
const stream = await window.getFakeVideoStream();
return stream;
};
});
// Close the browser
await browser.close();
})();
In this example, we first get the path of the fake video file using the path.join() method. We then use the context.grantPermissions() method to grant permission to the page to access the camera.
We then use the context.exposeBinding() method to expose a custom function named getFakeVideoStream() to the page. This function reads the video file from disk, creates a new MediaStream object, adds the video track from the file to the MediaStream object, and returns the MediaStream object.
Inside the page, we wait for the getUserMedia() method to be called using page.waitForFunction(), and then replace the getUserMedia() method with our custom function that returns the MediaStream object created from our fake video file.
Note that in this example, we've used 'camera' as the permission to grant to the page, assuming that the page is requesting access to the user's camera. If the page is requesting access to the user's microphone or other devices, you'll need to use the appropriate permission string instead.
MediaStream
Here's an example of how you can do this:
const { chromium } = require('playwright');
const path = require('path');
const fs = require('fs');
(async () => {
const browser = await chromium.launch();
const context = await browser.newContext();
// Get the path of your fake video file
const videoPath = path.join(__dirname, 'fake-video.mp4');
// Grant permission to the page to access the camera
await context.grantPermissions(['camera']);
// Intercept the getUserMedia method and return a MediaStream object created from the fake video file
await context.route('**/media/devices/getUserMedia', route => {
route.fulfill({
video: {
mandatory: {
chromeMediaSource: 'desktop',
chromeMediaSourceId: 'fake-video',
},
},
}).then(async () => {
const stream = fs.createReadStream(videoPath);
const videoStream = new MediaStream();
const videoTrack = videoStream.addTrack(stream.getVideoTracks()[0]);
await route.continue({
audio: false,
video: { width: 1280, height: 720, frameRate: 30, deviceId: videoTrack.id },
});
});
});
// Navigate to the page that requests access to the camera
const page = await context.newPage();
await page.goto('https://example.com');
// Close the browser
await browser.close();
})();
In this example, we first get the path of the fake video file using the path.join() method. We then use the context.grantPermissions() method to grant permission to the page to access the camera.
We then intercept the getUserMedia() method using the context.route() method. When the getUserMedia() method is called, we fulfill the request with a fake media stream that has a chromeMediaSource of desktop and chromeMediaSourceId of fake-video. We then create a new MediaStream object, add the video track from the file to the MediaStream object, and continue the request with the new MediaStream object.
Inside the page, the getUserMedia() method is not replaced, but when it is called, it will be intercepted and the fake video stream will be returned instead.
Note that this method intercepts all getUserMedia() requests, so if you want to only intercept requests from a specific page or URL, you can modify the context.route() method accordingly.
If you don't want to intercept the getUserMedia() method, you can use the navigator.mediaDevices.enumerateDevices() method to get a list of the available devices and then choose the device ID of your fake video file to pass to the getUserMedia() method.
Here's an example of how you can do this:
const { chromium } = require('playwright');
const path = require('path');
(async () => {
const browser = await chromium.launch();
const context = await browser.newContext();
// Get the path of your fake video file
const videoPath = path.join(__dirname, 'fake-video.mp4');
// Grant permission to the page to access the camera
await context.grantPermissions(['camera']);
// Get a list of the available devices
const devices = await context.grantPermissions(['camera']);
const videoDevices = devices.filter(device => device.kind === 'videoinput');
// Get the device ID of your fake video file
const fakeVideoDeviceId = 'fake-video';
// Pass the device ID of your fake video file to the getUserMedia() method
await context.newPage().then(async (page) => {
await page.goto('https://example.com');
const stream = await context.newCDPSession(page).then(async (cdp) => {
await cdp.send('Emulation.setDeviceMetricsOverride', {
width: 1280,
height: 720,
deviceScaleFactor: 0,
mobile: false,
});
await cdp.send('Emulation.clearDeviceMetricsOverride');
return await page.evaluate(async (fakeVideoDeviceId) => {
const devices = await navigator.mediaDevices.enumerateDevices();
const videoDevices = devices.filter(device => device.kind === 'videoinput');
const constraints = {
audio: false,
video: {
deviceId: videoDevices.find(device => device.deviceId === fakeVideoDeviceId)?.deviceId,
},
};
return await navigator.mediaDevices.getUserMedia(constraints);
}, fakeVideoDeviceId);
});
const videoElement = await page.$('video');
await videoElement.evaluate((video, stream) => {
video.srcObject = stream;
video.play();
}, stream);
await page.waitForTimeout(5000); // wait for 5 seconds
await page.close();
});
// Close the browser
await browser.close();
})();
In this example, we first get the path of the fake video file using the path.join() method. We then use the context.grantPermissions() method to grant permission to the page to access the camera.
We then use the navigator.mediaDevices.enumerateDevices() method to get a list of the available devices and filter out the video devices. We then get the device ID of your fake video file and pass it to the getUserMedia() method using the deviceId property of the video constraints.
Inside the page, we create a new MediaStream object using the getUserMedia() method and set the srcObject property of the video element to the MediaStream object.
Note that this method assumes that the page has a video element where the video stream will be displayed. If the page does not have a video element, you will need to modify the code to create a video element and append it to the page.