Summer Sale! All accounts are 50% off this week.

david001's avatar

Laravel dusk: how to switch between different browser tabs

I am in a situation where I have click the view button and it open another tab (_target) I need to verify if there is some text or not and then come back to original tab. Actually when we click view button , it ones new tab. so now i have two tabs and after verifying text in new tab i need to come to original tab where i have view button

 $this->browse(function (Browser $browser) {
            $browser->loginAs(User::find(1))
                //.....
                ->click('.savebutton')
                ->click('.view-page')
				->assertSee('sometext');

can anyone give me some tips? Thanks

0 likes
4 replies
piljac1's avatar
piljac1
Best Answer
Level 28

As stated by deleugpn in this Github issue, you can do the following to switch to the last opened tab (probably what you did already):

// Collect all tabs and grab the last one (recently opened).
$window = collect($browser->driver->getWindowHandles())->last();

// Switch to the new tab that contains the screenshot
$browser->driver->switchTo()->window($window);

Now for the part of going back to the original tab, I'll take a guess based on the source code that I read (I'm not using Dusk myself, but looking into it haha). In the source code, in addition to the getWindowHandles() method, there is also a singular version (getWindowHandle()), which returns the current window (tab). So you could probably store the result of $browser->driver->getWindowHandle() in a variable (say $originalWindow) before switching to the newly opened tab, and then call $browser->driver->switchTo()->window($originalWindow); when you're done with your assertions on the new tab.

1 like
david001's avatar

Thanks @piljac1 , I tried something like that from GitHub, but it didn't work for me. The steps you mentioned above are very clear and easy to understand. It worked for me. Thanks

aljaste's avatar

@piljac1 Can confirm, this does in fact work as expected. Seems to be a tad bit slow, however. I don't need to switch back, however, so I didn't experiment with that.

Please or to participate in this conversation.