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)
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', 'login@email.com')
->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));
}