Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Dusk - Reuse browser with its session and cookies

I've just used Laravel Dusk to test a javascript site.

Want to reuse the current browser with its session and cookies for some reason (keep me logged in on the site), so I don't need to pass auth process.

Any way to reuse the current browser?

I've already searched about this, but I found no practical info/example. Note: I use Dusk by default with Google Chrome and a standalone ChromeDriver (not Selenium)

like image 923
Arie Pratama Avatar asked Jun 30 '18 01:06

Arie Pratama


2 Answers

I had the same requirement using Laravel Dusk. The trick is to use the Facebook/WebDriver/Remote/RemoteWebDriver class and its manage() method.

Pseudo code:

use Facebook\WebDriver\Chrome\ChromeOptions;
use Facebook\WebDriver\Remote\DesiredCapabilities;
use Facebook\WebDriver\Remote\RemoteWebDriver;
use Facebook\WebDriver\Cookie;
use Facebook\WebDriver\WebDriverOptions;
use Laravel\Dusk\Browser;
use Laravel\Dusk\Chrome\ChromeProcess;

//the cookie file name
$cookie_file = 'cookies.txt';

//create the driver
$process = (new ChromeProcess)->toProcess();
$process->start();
$options = (new ChromeOptions)->addArguments(['--disable-gpu','--enable-file-cookies','--no-sandbox']);
$capabilities = DesiredCapabilities::chrome()->setCapability(ChromeOptions::CAPABILITY, $options);
$driver = retry(5, function () use($capabilities) {
    return RemoteWebDriver::create('http://localhost:9515', $capabilities);
}, 50); 

//start the browser
$browser = new Browser($driver);
$browser->visit('https://tehwebsite.com/login');

//Cookie management - if there's a stored cookie file, load the contents         
if (file_exists($cookie_file)) {
    //Get cookies from storage
    $cookies = unserialize(file_get_contents($cookie_file));
    //Add each cookie to this session
    foreach ($cookies as $key => $cookie) {
        $driver->manage()->addCookie($cookie);
    }
}

//if no cookies in storage, do the browser tasks that will create them, eg by logging in 
$browser
    ->type('email', '[email protected]')
    ->type('password', 'sdfsdfsdf')
    ->check('rememberMe')
    ->click('#login');

//now the cookies have been set, get and store them for future runs
if (!file_exists($cookie_file)) {
    $cookies = $driver->manage()->getCookies();
    file_put_contents($cookie_file, serialize($cookies));
}
like image 102
Anthony Avatar answered Oct 03 '22 19:10

Anthony


When you use laravel dusk, i found a way to setcookie to the brower:

Use the visits twice when use planCookie function like below code:


$this->browse(function (Browser $browser) {
    $url = 'https://google.com';
    $browser->visit($url);
    $browser->plainCookie('key', 'value');
    $browser->visit($url);
    $browser->assertSee('Some Text');
});

Hope this helpful.

like image 26
Avenger Avatar answered Oct 03 '22 21:10

Avenger