I’ve encountered an issue with Laravel Dusk tests not triggering the onbeforeunload
event when navigating away from a page. This behavior differs from what I observe when manually interacting with the page in a browser.
Steps To Reproduce
Create a route that returns an HTML page with an onbeforeunload
event handler:
Route::get('/leave', function () {
return '<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Page</title>
</head>
<body>
<h1 id="head">Test page</h1>
<a href="/">page</a>
<script>
window.onbeforeunload = function(e) {
e = e || window.event;
if (e) {
e.returnValue = "Go?";
}
return "Go?";
};
</script>
</body>
</html>';
});
Create a Dusk test that visits this page:
phpCopypublic function testLeave(): void
{
$this->browse(function (Browser $browser) {
$browser->visit('/leave')
->pause(15000);
});
}
Run the Dusk test.
Expected behavior:
When the test navigates away from the page (either by clicking the link or using Dusk’s navigation methods), it should trigger the onbeforeunload event and show a confirmation dialog.
Actual behavior:
The onbeforeunload event is not triggered, and no confirmation dialog is shown when the test navigates away from the page. This occurs both when clicking the link programmatically and when using Dusk’s built-in navigation methods.
Additional information:
This issue was not present in Laravel 10 with Dusk 7, where the test successfully triggered the onbeforeunload event.
The onbeforeunload event works as expected when manually interacting with the page in a browser.
For manual verification, I removed the –headless=new parameter in the DuskTestCase.php file to observe the browser behavior directly.
Could you please investigate this issue and provide guidance on how to properly test onbeforeunload events in Laravel 11 with Dusk?
Dusk Version: 8.2.6
Laravel Version: 11.25
PHP Version: 8.3.3
PHPUnit Version: 11.3.6