blog and things oh hi there!
How does Laravel Dusk work?

Dusk was just recently introduced along with Laravel 5.4 and I wanted to take a deeper look into which external tools were being utilized and how I can use these to create scripts that would perform trivial tasks within a browser. Here is what I found out.

Laravel Dusk uses two main tools to get set up. First, ChromeDriver is used as a Google Chrome instance. This replaces the need for a Java/Selenium standalone server. The other half of Laravel Dusk uses Facebook's PHP WebDriver and this library serves as a wrapper for Selenium and therefore goes hand in hand with ChromeDriver.

To get started, begin by downloading the ChromeDriver binary. Once this is done, create a composer.json file and add the following:

{
    "require": {
        "facebook/webdriver": "^1.2"
    }
}

With both of these in hand, we can start to program actions against a Google Chrome instance. In this simple Search class, I'll launch a ChromeDriver instance, visit Google, type some text into the search box and take a screen shot of the results. Here is what goes into search.php:

<?php

require __DIR__.'/vendor/autoload.php';

use Facebook\WebDriver\Chrome\ChromeDriver;
use Facebook\WebDriver\Chrome\ChromeOptions;
use Facebook\WebDriver\Remote\DesiredCapabilities;
use Facebook\WebDriver\WebDriverBy;

putenv('webdriver.chrome.driver=/path/to/ChromeDriver/binary/file');

class Search
{
    private $options;
    private $caps;
    private $chrome;

    public function __construct()
    {
        $this->options = new ChromeOptions();
        $this->caps = DesiredCapabilities::chrome();

        $this->setOptions();
        $this->setCaps();
        $this->boot();
    }

    public function __destruct()
    {
        return $this->chrome->quit();
    }

    protected function setOptions()
    {
        return $this->options->addArguments([
            '--user-data-dir=/Users/kjung/Library/Application Support/Google/Chrome/Profile 1/',
            '--disable-popup-blocking',
        ]);
    }

    protected function setCaps()
    {
        return $this->caps->setCapability(ChromeOptions::CAPABILITY, $this->options);
    }

    public function boot()
    {
        return $this->chrome = ChromeDriver::start($this->caps);
    }

    public function text(string $text)
    {
        $this->chrome->get('https://google.ca/');
        $this->chrome->findElement(WebDriverBy::className('gsfi'))->sendKeys($text."\n");
        $this->chrome->takeScreenshot('screenshot.png');
    }
}

$search = new Search;
$search->text('laravel dusk');

Of course you can call this with php search.php.

Here are some good resources to get you started:

© 2019 Kevin Jung