Laravel Dusk - how to fake camera to stream media

Published on Jul 10, 2022

In this post, I will show you how can you simulate a fake camera by replacing it with an image or a video.

Lets begin with the webdriver settings.

protected function driver(): RemoteWebDriver
    {
        $options = (new ChromeOptions)->addArguments(collect([
            '--start-maximized',
            // this is used for faking camera for chrome
            '--use-fake-device-for-media-stream',
            // this is used for add custom media to the camera
            '--use-file-for-fake-video-capture=' . base_path('tests' . DIRECTORY_SEPARATOR . 'Files' . DIRECTORY_SEPARATOR . 'qr.mjpeg'),
        ])->unless($this->hasHeadlessDisabled(), function ($items) {
            return $items->merge([
                '--disable-gpu',
                '--headless',
                '--window-size=1920,1080',
            ]);
        })->all())->setExperimentalOption('prefs', [
            // Enable camera (0 - Default, 1 - Allow, 2 - Block)
            'profile.default_content_setting_values.media_stream_camera' => 1,
        ]);

        return RemoteWebDriver::create(
            env('DUSK_DRIVER_URL') ?? 'http://localhost:9515',
            DesiredCapabilities::chrome()->setCapability(
                ChromeOptions::CAPABILITY, $options
            )
        );
    }

For media I have tried to upload .jpg or .png but this types don't work. What worked for me was mjpeg. So what I did was, I converted the .mp4 file to .mjpeg with convertio.co. When you have the media, place it to your test/Files folder and name it to whatever you like, but change the file name in the 8th line of the previous code.

Now when your application asks to allow camera it will automatically allow it.