Tests: Make the beforeunload event tests work regardless of extensions

Some browser extensions, like React DevTools, send messages to the content area.
Since our beforeunload event test listens for all messages, it used to catch
those as well, failing the test.

Add a `source` field to the payload JSON and check for it before treating the
message as coming from our own test to make sure the test passes even with such
browser extensions installed.

Closes gh-5478
This commit is contained in:
Michał Gołębiowski-Owczarek 2024-04-25 00:24:55 +02:00 committed by GitHub
parent 7cdd837423
commit 399a78ee9f
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 20 additions and 10 deletions

View File

@ -4,17 +4,18 @@
<script> <script>
function report( event ) { function report( event ) {
var payload = { var payload = {
source: "jQuery onbeforeunload iframe test",
event: event.type event: event.type
}; };
return parent.postMessage( JSON.stringify(payload), "*" ); return parent.postMessage( JSON.stringify( payload ), "*" );
} }
jQuery( window ).on( "beforeunload", function( event ) { jQuery( window ).on( "beforeunload", function( event ) {
report( event ); report( event );
}).on( "load", function( event ) { } ).on( "load", function( event ) {
setTimeout(function() { setTimeout( function() {
window.location.reload(); window.location.reload();
}, 50); }, 50 );
}); } );
</script> </script>
</html> </html>

View File

@ -1448,13 +1448,22 @@ QUnit[ /(ipad|iphone|ipod)/i.test( navigator.userAgent ) ? "skip" : "test" ](
var done = assert.async(); var done = assert.async();
window.onmessage = function( event ) { window.onmessage = function( event ) {
try {
var payload = JSON.parse( event.data ); var payload = JSON.parse( event.data );
// Ignore unrelated messages
if ( payload.source === "jQuery onbeforeunload iframe test" ) {
assert.ok( payload.event, "beforeunload", "beforeunload event" ); assert.ok( payload.event, "beforeunload", "beforeunload event" );
iframe.remove(); iframe.remove();
window.onmessage = null; window.onmessage = null;
done(); done();
}
} catch ( e ) {
// Messages may come from other sources, like browser extensions;
// some may not be valid JSONs and thus cannot be `JSON.parse`d.
}
}; };
iframe.appendTo( "#qunit-fixture" ); iframe.appendTo( "#qunit-fixture" );