browser_ua_emulation.js (2887B)
1 /* Any copyright is dedicated to the Public Domain. 2 http://creativecommons.org/publicdomain/zero/1.0/ */ 3 4 "use strict"; 5 6 const HTML = ` 7 <h1>Test browser user agent emulation</h1> 8 <iframe id='test-iframe'></iframe> 9 `; 10 const URL = `https://example.com/document-builder.sjs?html=${encodeURI(HTML)}`; 11 12 // Test that the docShell UA emulation works 13 async function contentTaskNoOverride() { 14 let docshell = docShell; 15 is( 16 docshell.browsingContext.customUserAgent, 17 "", 18 "There should initially be no customUserAgent" 19 ); 20 21 return content.navigator.userAgent; 22 } 23 24 async function contentTaskOverride() { 25 let docshell = docShell; 26 is( 27 docshell.browsingContext.customUserAgent, 28 "foo", 29 "The user agent should be changed to foo" 30 ); 31 32 is( 33 content.navigator.userAgent, 34 "foo", 35 "The user agent should be changed to foo" 36 ); 37 38 let frameWin = content.document.querySelector("#test-iframe").contentWindow; 39 is( 40 frameWin.navigator.userAgent, 41 "foo", 42 "The UA should be passed on to frames." 43 ); 44 45 let newFrame = content.document.createElement("iframe"); 46 content.document.body.appendChild(newFrame); 47 48 let newFrameWin = newFrame.contentWindow; 49 is( 50 newFrameWin.navigator.userAgent, 51 "foo", 52 "Newly created frames should use the new UA" 53 ); 54 55 newFrameWin.location.reload(); 56 await ContentTaskUtils.waitForEvent(newFrame, "load"); 57 58 is( 59 newFrameWin.navigator.userAgent, 60 "foo", 61 "New UA should persist across reloads" 62 ); 63 } 64 65 async function contentTaskCleared(initialUA) { 66 is( 67 docShell.browsingContext.customUserAgent, 68 "", 69 "customUserAgent was cleared" 70 ); 71 72 is(content.navigator.userAgent, initialUA, "document has the initial UA"); 73 } 74 75 add_task(async function () { 76 await BrowserTestUtils.withNewTab( 77 { gBrowser, url: URL }, 78 async function (browser) { 79 const initialUA = await SpecialPowers.spawn( 80 browser, 81 [], 82 contentTaskNoOverride 83 ); 84 85 let browsingContext = BrowserTestUtils.getBrowsingContextFrom(browser); 86 browsingContext.customUserAgent = "foo"; 87 88 await SpecialPowers.spawn(browser, [], contentTaskOverride); 89 90 info( 91 "Check that clearing customUserAgent resets userAgent to its initial value" 92 ); 93 94 // First we need to reload the page, as the user agent can be retrieved from the User-Agent header. 95 browser.reload(); 96 await BrowserTestUtils.browserLoaded(browser); 97 98 browsingContext.customUserAgent = ""; 99 await SpecialPowers.spawn(browser, [initialUA], contentTaskCleared); 100 101 // A second reload should reset the User-Agent header, and make navigate.userAgent correct again. 102 browser.reload(); 103 await BrowserTestUtils.browserLoaded(browser); 104 105 browsingContext.customUserAgent = ""; 106 await SpecialPowers.spawn(browser, [initialUA], contentTaskCleared); 107 } 108 ); 109 });