browser_onbeforeunload_only_after_interaction.js (2265B)
1 const { PromptTestUtils } = ChromeUtils.importESModule( 2 "resource://testing-common/PromptTestUtils.sys.mjs" 3 ); 4 5 function pageScript() { 6 window.addEventListener( 7 "beforeunload", 8 function (event) { 9 var str = "Some text that causes the beforeunload dialog to be shown"; 10 event.returnValue = str; 11 return str; 12 }, 13 true 14 ); 15 } 16 17 SpecialPowers.pushPrefEnv({ 18 set: [["dom.require_user_interaction_for_beforeunload", true]], 19 }); 20 21 const PAGE_URL = 22 "data:text/html," + 23 encodeURIComponent("<script>(" + pageScript.toSource() + ")();</script>"); 24 25 add_setup(async function () { 26 await SpecialPowers.pushPrefEnv({ 27 set: [["test.wait300msAfterTabSwitch", true]], 28 }); 29 }); 30 31 add_task(async function doClick() { 32 // The onbeforeunload dialog should appear. 33 let dialogPromise = PromptTestUtils.waitForPrompt(null, { 34 modalType: Services.prompt.MODAL_TYPE_CONTENT, 35 promptType: "confirmEx", 36 }); 37 38 let openPagePromise = openPage(true); 39 let dialog = await dialogPromise; 40 Assert.ok(true, "Showed the beforeunload dialog."); 41 42 await PromptTestUtils.handlePrompt(dialog, { buttonNumClick: 0 }); 43 await openPagePromise; 44 }); 45 46 add_task(async function noClick() { 47 // The onbeforeunload dialog should NOT appear. 48 await openPage(false); 49 info("If we time out here, then the dialog was shown..."); 50 }); 51 52 async function openPage(shouldClick) { 53 // Open about:blank in a new tab. 54 await BrowserTestUtils.withNewTab( 55 { gBrowser, url: "about:blank" }, 56 async function (browser) { 57 // Load the page. 58 BrowserTestUtils.startLoadingURIString(browser, PAGE_URL); 59 await BrowserTestUtils.browserLoaded(browser); 60 61 if (shouldClick) { 62 await BrowserTestUtils.synthesizeMouse("body", 2, 2, {}, browser); 63 } 64 let hasInteractedWith = await SpecialPowers.spawn( 65 browser, 66 [""], 67 function () { 68 return content.document.hasBeenUserGestureActivated; 69 } 70 ); 71 is( 72 shouldClick, 73 hasInteractedWith, 74 "Click should update document interactivity state" 75 ); 76 // And then navigate away. 77 BrowserTestUtils.startLoadingURIString(browser, "http://example.com/"); 78 await BrowserTestUtils.browserLoaded(browser); 79 } 80 ); 81 }