Skip to content

Commit 399a78e

Browse files
authored
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
1 parent 7cdd837 commit 399a78e

File tree

2 files changed

+20
-10
lines changed

2 files changed

+20
-10
lines changed

test/data/event/onbeforeunload.html

+6-5
Original file line numberDiff line numberDiff line change
@@ -4,17 +4,18 @@
44
<script>
55
function report( event ) {
66
var payload = {
7+
source: "jQuery onbeforeunload iframe test",
78
event: event.type
89
};
9-
return parent.postMessage( JSON.stringify(payload), "*" );
10+
return parent.postMessage( JSON.stringify( payload ), "*" );
1011
}
1112

1213
jQuery( window ).on( "beforeunload", function( event ) {
1314
report( event );
14-
}).on( "load", function( event ) {
15-
setTimeout(function() {
15+
} ).on( "load", function( event ) {
16+
setTimeout( function() {
1617
window.location.reload();
17-
}, 50);
18-
});
18+
}, 50 );
19+
} );
1920
</script>
2021
</html>

test/unit/event.js

+14-5
Original file line numberDiff line numberDiff line change
@@ -1448,13 +1448,22 @@ QUnit[ /(ipad|iphone|ipod)/i.test( navigator.userAgent ) ? "skip" : "test" ](
14481448
var done = assert.async();
14491449

14501450
window.onmessage = function( event ) {
1451-
var payload = JSON.parse( event.data );
1451+
try {
1452+
var payload = JSON.parse( event.data );
14521453

1453-
assert.ok( payload.event, "beforeunload", "beforeunload event" );
1454+
// Ignore unrelated messages
1455+
if ( payload.source === "jQuery onbeforeunload iframe test" ) {
1456+
assert.ok( payload.event, "beforeunload", "beforeunload event" );
14541457

1455-
iframe.remove();
1456-
window.onmessage = null;
1457-
done();
1458+
iframe.remove();
1459+
window.onmessage = null;
1460+
done();
1461+
}
1462+
} catch ( e ) {
1463+
1464+
// Messages may come from other sources, like browser extensions;
1465+
// some may not be valid JSONs and thus cannot be `JSON.parse`d.
1466+
}
14581467
};
14591468

14601469
iframe.appendTo( "#qunit-fixture" );

0 commit comments

Comments
 (0)