Laravel Dusk-重用带有会话和cookie的浏览器 [英] Laravel Dusk - Reuse browser with its session and cookies

查看:105
本文介绍了Laravel Dusk-重用带有会话和cookie的浏览器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚用Laravel Dusk测试了一个JavaScript网站.

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

出于某种原因(希望我在网站上登录),希望将当前的浏览器及其会话和cookie重复使用,因此我不需要通过身份验证过程.

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?

我已经搜索过有关此内容的信息,但没有发现任何实用的信息/示例. 注意:默认情况下,我在Google Chrome和独立的ChromeDriver(不是Selenium)上使用Dusk

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)

推荐答案

我使用Laravel Dusk具有相同的要求.诀窍是使用Facebook/WebDriver/Remote/RemoteWebDriver类及其

I had the same requirement using Laravel Dusk. The trick is to use the Facebook/WebDriver/Remote/RemoteWebDriver class and its 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));
}

这篇关于Laravel Dusk-重用带有会话和cookie的浏览器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆