繁体   English   中英

Laravel Dusk - 重用浏览器及其会话和 cookie

[英]Laravel Dusk - Reuse browser with its session and cookies

我刚刚使用 Laravel Dusk 测试了一个 javascript 站点。

出于某种原因想要重用当前浏览器及其会话和 cookie(让我保持在站点上的登录状态),所以我不需要通过身份验证过程。

有什么办法可以重用当前的浏览器?

我已经搜索过这个,但我没有找到实用的信息/示例。 注意:我默认使用 Dusk 和 Google Chrome 和一个独立的 ChromeDriver(不是 Selenium)

我使用 Laravel Dusk 也有同样的要求。 诀窍是使用 Facebook/WebDriver/Remote/RemoteWebDriver 类及其manage() 方法

伪代码:

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 设置为浏览器的方法:

使用planCookie函数时使用两次访问,如下代码:


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

希望这有帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM