Skip to content

Instantly share code, notes, and snippets.

@egyleader
Created September 21, 2020 15:31
Show Gist options
  • Save egyleader/92e7bab83e7414b6840d52fedd30ff49 to your computer and use it in GitHub Desktop.
Save egyleader/92e7bab83e7414b6840d52fedd30ff49 to your computer and use it in GitHub Desktop.
A collection of Useful Helpers For Laravel Dusk Browser Automations
<?php
namespace Tests\Browser\Helpers;
use Laravel\Dusk\Browser;
/** A collection of Useful Helpers For Laravel Dusk Browser Automations
* Just put the file in your project and call Helpers::functionName($arguments)
* feel free to extend it and add your useful helpers
* @copyright 2020 egyleader
*/
class Helpers
{
/**
* Get the last opened tab in focus
*
* @param Browser $browser
*/
public static function lastTab(Browser $browser)
{
$window = collect($browser->driver->getWindowHandles())->last();
$browser->driver->switchTo()->window($window);
}
/**
* Get the first opened tab in focus
*
* @param Browser $browser
*/
public static function firstTab(Browser $browser)
{
$window = collect($browser->driver->getWindowHandles())->first();
$browser->driver->switchTo()->window($window);
}
/**
* Opens given link in new tab and focuse on it
*
* @param Browser $browser
* @param String $url
*/
public static function openInTab(Browser $browser, $url)
{
$browser->script('window.open("'.$url.'" , "_blank")');
Helpers::lastTab($browser);
}
/**
* Close current tab in focus
*
* @param Browser $browser
*/
public static function closeTab(Browser $browser)
{
$browser->script("window.close('', '_parent', '');");
Helpers::lastTab($browser);
}
/**
* Check if logged in to site by checking for stored cookie file
* if there is a cookie it injects it into browser
* ,redirects to the redirect link and return true
* if not it returns false
*
* @param Browser $browser
* @param string $baseUrl
* @param string $redirectUrl
* @param string $cookie_file
* @return Boolean
*/
public static function isLoggedIn(Browser $browser, $baseUrl, $redirectUrl, $cookie_file)
{
$cookie_file =storage_path($cookie_file);
if (file_exists($cookie_file)) {
$browser->visit($baseUrl);
//Get cookies from storage
$cookies = unserialize(file_get_contents($cookie_file));
//Add each cookie to this session
foreach ($cookies as $cookie) {
$browser->driver->manage()->addCookie($cookie);
}
$browser->visit($redirectUrl);
return true;
} else {
return false ;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment