我刚刚使用Laravel Dusk测试了一个JavaScript网站。
出于某种原因(希望我在网站上登录),希望通过其会话和cookie重用当前的浏览器,所以我不需要通过身份验证过程。
可以重用当前浏览器吗?
我已经搜索过有关此内容的信息,但没有找到实际的信息/示例。 注意:默认情况下,我在Google Chrome和独立的ChromeDriver(不是Selenium)上使用Dusk
答案 0 :(得分:0)
我对Laravel Dusk有相同的要求。诀窍是使用Facebook / WebDriver / Remote / RemoteWebDriver类及其manage() method。
伪代码:
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));
}
答案 1 :(得分:0)
当您使用Laravel黄昏时,我找到了一种将cookie设置为浏览器的方法:
在使用如下代码的planCookie函数时使用两次访问:
$this->browse(function (Browser $browser) {
$url = 'https://google.com';
$browser->visit($url);
$browser->plainCookie('key', 'value');
$browser->visit($url);
$browser->assertSee('Some Text');
});
希望这会有所帮助。