Summer Sale! All accounts are 50% off this week.

piljac1's avatar
Level 28

Managing browser permissions with Laravel Dusk

Hi guys! Total Laravel Dusk noob here (started using it today). I wanted to test a "copy link" on the Web app I'm working on and I ran into browser permissions issues when trying to access the clipboard content while testing. Of course, that default behavior makes sense, because Google Chrome prompts the user and ask for permission to access the clipboard. However, I haven't found a way to tell Dusk to enable specific permissions. I found the following Cypress example that is probably the appropriate way of doing it, but I don't know if there's a Dusk equivalent.

cy.wrap(Cypress.automation('remote:debugger:protocol', {
  command: 'Browser.grantPermissions',
  params: {
    permissions: ['clipboardReadWrite', 'clipboardSanitizedWrite'],
    origin: window.location.origin,
  },
}))

Thanks in advance!

0 likes
1 reply
N30's avatar

After 5 hours of reading the vendor code for dusk I was able to figure it out, here is the working code that worked for me in Laravel 9 and 10.

Inside DuskTestCase.php

use Facebook\WebDriver\Chrome\ChromeDevToolsDriver;

 protected function grantPermission( \Laravel\Dusk\Browser $browser )
    {
        try {
            $driver = $browser->driver;
            $devtools = new ChromeDevToolsDriver($driver);

            $result = $devtools->execute('Browser.grantPermissions', [
                "permissions" =>  ["clipboardReadWrite", "clipboardSanitizedWrite"],
            ]);

            return $result;
        } catch (\Exception) {
            return null;
        }
    }

    public   function testClipboard()
    {
        $this->browse(function ( \Laravel\Dusk\Browser $browser) {

            $this->grantPermission($browser );

            // Your test flow and assertion
        });
    }

Then in your Tests when you open the browser closure you will make call to this via parent since it is an extension of this abstract class:

class WhateverItis extends DuskTestCase
{
    /**
     * A Dusk test example.
     */ 
    protected $preserveGlobalState = FALSE;
    protected $runTestInSeparateProcess = TRUE;


    public function testExample(): void
    {

$this->browse(function (Browser $browser) use ($reviews, $selector_map, $biz, $dusk) {

 parent::testClipboard($browser);

 $clipboard_data = $browser->script("return navigator.clipboard.readText();");

...rest of code

Please or to participate in this conversation.