wkPage.js 55 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.WKPage = void 0;
  6. var _path = _interopRequireDefault(require("path"));
  7. var _utilsBundle = require("../../utilsBundle");
  8. var _stackTrace = require("../../utils/stackTrace");
  9. var _utils = require("../../utils");
  10. var _hostPlatform = require("../../utils/hostPlatform");
  11. var dialog = _interopRequireWildcard(require("../dialog"));
  12. var dom = _interopRequireWildcard(require("../dom"));
  13. var _eventsHelper = require("../../utils/eventsHelper");
  14. var _helper = require("../helper");
  15. var network = _interopRequireWildcard(require("../network"));
  16. var _page = require("../page");
  17. var _wkAccessibility = require("./wkAccessibility");
  18. var _wkConnection = require("./wkConnection");
  19. var _wkExecutionContext = require("./wkExecutionContext");
  20. var _wkInput = require("./wkInput");
  21. var _wkInterceptableRequest = require("./wkInterceptableRequest");
  22. var _wkProvisionalPage = require("./wkProvisionalPage");
  23. var _wkWorkers = require("./wkWorkers");
  24. var _debugLogger = require("../../common/debugLogger");
  25. var _manualPromise = require("../../utils/manualPromise");
  26. var _browserContext = require("../browserContext");
  27. var _errors = require("../errors");
  28. function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
  29. function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
  30. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  31. /**
  32. * Copyright 2017 Google Inc. All rights reserved.
  33. * Modifications copyright (c) Microsoft Corporation.
  34. *
  35. * Licensed under the Apache License, Version 2.0 (the "License");
  36. * you may not use this file except in compliance with the License.
  37. * You may obtain a copy of the License at
  38. *
  39. * http://www.apache.org/licenses/LICENSE-2.0
  40. *
  41. * Unless required by applicable law or agreed to in writing, software
  42. * distributed under the License is distributed on an "AS IS" BASIS,
  43. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  44. * See the License for the specific language governing permissions and
  45. * limitations under the License.
  46. */
  47. const UTILITY_WORLD_NAME = '__playwright_utility_world__';
  48. class WKPage {
  49. constructor(browserContext, pageProxySession, opener) {
  50. this.rawMouse = void 0;
  51. this.rawKeyboard = void 0;
  52. this.rawTouchscreen = void 0;
  53. this._session = void 0;
  54. this._provisionalPage = null;
  55. this._page = void 0;
  56. this._pagePromise = new _manualPromise.ManualPromise();
  57. this._pageProxySession = void 0;
  58. this._opener = void 0;
  59. this._requestIdToRequest = new Map();
  60. this._requestIdToRequestWillBeSentEvent = new Map();
  61. this._workers = void 0;
  62. this._contextIdToContext = void 0;
  63. this._sessionListeners = [];
  64. this._eventListeners = void 0;
  65. this._browserContext = void 0;
  66. this._initializedPage = null;
  67. this._firstNonInitialNavigationCommittedPromise = void 0;
  68. this._firstNonInitialNavigationCommittedFulfill = () => {};
  69. this._firstNonInitialNavigationCommittedReject = e => {};
  70. this._lastConsoleMessage = null;
  71. this._requestIdToResponseReceivedPayloadEvent = new Map();
  72. // Holds window features for the next popup being opened via window.open,
  73. // until the popup page proxy arrives.
  74. this._nextWindowOpenPopupFeatures = void 0;
  75. this._recordingVideoFile = null;
  76. this._screencastGeneration = 0;
  77. this._pageProxySession = pageProxySession;
  78. this._opener = opener;
  79. this.rawKeyboard = new _wkInput.RawKeyboardImpl(pageProxySession);
  80. this.rawMouse = new _wkInput.RawMouseImpl(pageProxySession);
  81. this.rawTouchscreen = new _wkInput.RawTouchscreenImpl(pageProxySession);
  82. this._contextIdToContext = new Map();
  83. this._page = new _page.Page(this, browserContext);
  84. this.rawMouse.setPage(this._page);
  85. this._workers = new _wkWorkers.WKWorkers(this._page);
  86. this._session = undefined;
  87. this._browserContext = browserContext;
  88. this._page.on(_page.Page.Events.FrameDetached, frame => this._removeContextsForFrame(frame, false));
  89. this._eventListeners = [_eventsHelper.eventsHelper.addEventListener(this._pageProxySession, 'Target.targetCreated', this._onTargetCreated.bind(this)), _eventsHelper.eventsHelper.addEventListener(this._pageProxySession, 'Target.targetDestroyed', this._onTargetDestroyed.bind(this)), _eventsHelper.eventsHelper.addEventListener(this._pageProxySession, 'Target.dispatchMessageFromTarget', this._onDispatchMessageFromTarget.bind(this)), _eventsHelper.eventsHelper.addEventListener(this._pageProxySession, 'Target.didCommitProvisionalTarget', this._onDidCommitProvisionalTarget.bind(this)), _eventsHelper.eventsHelper.addEventListener(this._pageProxySession, 'Screencast.screencastFrame', this._onScreencastFrame.bind(this))];
  90. this._firstNonInitialNavigationCommittedPromise = new Promise((f, r) => {
  91. this._firstNonInitialNavigationCommittedFulfill = f;
  92. this._firstNonInitialNavigationCommittedReject = r;
  93. });
  94. if (opener && !browserContext._options.noDefaultViewport && opener._nextWindowOpenPopupFeatures) {
  95. const viewportSize = _helper.helper.getViewportSizeFromWindowFeatures(opener._nextWindowOpenPopupFeatures);
  96. opener._nextWindowOpenPopupFeatures = undefined;
  97. if (viewportSize) this._page._emulatedSize = {
  98. viewport: viewportSize,
  99. screen: viewportSize
  100. };
  101. }
  102. }
  103. potentiallyUninitializedPage() {
  104. return this._page;
  105. }
  106. async _initializePageProxySession() {
  107. if (this._page._browserContext.isSettingStorageState()) return;
  108. const promises = [this._pageProxySession.send('Dialog.enable'), this._pageProxySession.send('Emulation.setActiveAndFocused', {
  109. active: true
  110. })];
  111. const contextOptions = this._browserContext._options;
  112. if (contextOptions.javaScriptEnabled === false) promises.push(this._pageProxySession.send('Emulation.setJavaScriptEnabled', {
  113. enabled: false
  114. }));
  115. promises.push(this._updateViewport());
  116. promises.push(this.updateHttpCredentials());
  117. if (this._browserContext._permissions.size) {
  118. for (const [key, value] of this._browserContext._permissions) promises.push(this._grantPermissions(key, value));
  119. }
  120. if (this._browserContext._options.recordVideo) {
  121. const outputFile = _path.default.join(this._browserContext._options.recordVideo.dir, (0, _utils.createGuid)() + '.webm');
  122. promises.push(this._browserContext._ensureVideosPath().then(() => {
  123. return this._startVideo({
  124. // validateBrowserContextOptions ensures correct video size.
  125. ...this._browserContext._options.recordVideo.size,
  126. outputFile
  127. });
  128. }));
  129. }
  130. await Promise.all(promises);
  131. }
  132. _setSession(session) {
  133. _eventsHelper.eventsHelper.removeEventListeners(this._sessionListeners);
  134. this._session = session;
  135. this.rawKeyboard.setSession(session);
  136. this.rawMouse.setSession(session);
  137. this._addSessionListeners();
  138. this._workers.setSession(session);
  139. }
  140. // This method is called for provisional targets as well. The session passed as the parameter
  141. // may be different from the current session and may be destroyed without becoming current.
  142. async _initializeSession(session, provisional, resourceTreeHandler) {
  143. await this._initializeSessionMayThrow(session, resourceTreeHandler).catch(e => {
  144. // Provisional session can be disposed at any time, for example due to new navigation initiating
  145. // a new provisional page.
  146. if (provisional && session.isDisposed()) return;
  147. // Swallow initialization errors due to newer target swap in,
  148. // since we will reinitialize again.
  149. if (this._session === session) throw e;
  150. });
  151. }
  152. async _initializeSessionMayThrow(session, resourceTreeHandler) {
  153. const [, frameTree] = await Promise.all([
  154. // Page agent must be enabled before Runtime.
  155. session.send('Page.enable'), session.send('Page.getResourceTree')]);
  156. resourceTreeHandler(frameTree);
  157. const promises = [
  158. // Resource tree should be received before first execution context.
  159. session.send('Runtime.enable'), session.send('Page.createUserWorld', {
  160. name: UTILITY_WORLD_NAME
  161. }).catch(_ => {}),
  162. // Worlds are per-process
  163. session.send('Console.enable'), session.send('Network.enable'), this._workers.initializeSession(session)];
  164. if (this._page.needsRequestInterception()) {
  165. promises.push(session.send('Network.setInterceptionEnabled', {
  166. enabled: true
  167. }));
  168. promises.push(session.send('Network.setResourceCachingDisabled', {
  169. disabled: true
  170. }));
  171. promises.push(session.send('Network.addInterception', {
  172. url: '.*',
  173. stage: 'request',
  174. isRegex: true
  175. }));
  176. }
  177. if (this._page._browserContext.isSettingStorageState()) {
  178. await Promise.all(promises);
  179. return;
  180. }
  181. const contextOptions = this._browserContext._options;
  182. if (contextOptions.userAgent) promises.push(this.updateUserAgent());
  183. const emulatedMedia = this._page.emulatedMedia();
  184. if (emulatedMedia.media || emulatedMedia.colorScheme || emulatedMedia.reducedMotion || emulatedMedia.forcedColors) promises.push(WKPage._setEmulateMedia(session, emulatedMedia.media, emulatedMedia.colorScheme, emulatedMedia.reducedMotion, emulatedMedia.forcedColors));
  185. for (const binding of this._page.allBindings()) promises.push(session.send('Runtime.addBinding', {
  186. name: binding.name
  187. }));
  188. const bootstrapScript = this._calculateBootstrapScript();
  189. if (bootstrapScript.length) promises.push(session.send('Page.setBootstrapScript', {
  190. source: bootstrapScript
  191. }));
  192. this._page.frames().map(frame => frame.evaluateExpression(bootstrapScript).catch(e => {}));
  193. if (contextOptions.bypassCSP) promises.push(session.send('Page.setBypassCSP', {
  194. enabled: true
  195. }));
  196. const emulatedSize = this._page.emulatedSize();
  197. if (emulatedSize) {
  198. promises.push(session.send('Page.setScreenSizeOverride', {
  199. width: emulatedSize.screen.width,
  200. height: emulatedSize.screen.height
  201. }));
  202. }
  203. promises.push(this.updateEmulateMedia());
  204. promises.push(session.send('Network.setExtraHTTPHeaders', {
  205. headers: (0, _utils.headersArrayToObject)(this._calculateExtraHTTPHeaders(), false /* lowerCase */)
  206. }));
  207. if (contextOptions.offline) promises.push(session.send('Network.setEmulateOfflineState', {
  208. offline: true
  209. }));
  210. promises.push(session.send('Page.setTouchEmulationEnabled', {
  211. enabled: !!contextOptions.hasTouch
  212. }));
  213. if (contextOptions.timezoneId) {
  214. promises.push(session.send('Page.setTimeZone', {
  215. timeZone: contextOptions.timezoneId
  216. }).catch(e => {
  217. throw new Error(`Invalid timezone ID: ${contextOptions.timezoneId}`);
  218. }));
  219. }
  220. if (this._page.fileChooserIntercepted()) promises.push(session.send('Page.setInterceptFileChooserDialog', {
  221. enabled: true
  222. }));
  223. promises.push(session.send('Page.overrideSetting', {
  224. setting: 'DeviceOrientationEventEnabled',
  225. value: contextOptions.isMobile
  226. }));
  227. promises.push(session.send('Page.overrideSetting', {
  228. setting: 'FullScreenEnabled',
  229. value: !contextOptions.isMobile
  230. }));
  231. promises.push(session.send('Page.overrideSetting', {
  232. setting: 'NotificationsEnabled',
  233. value: !contextOptions.isMobile
  234. }));
  235. promises.push(session.send('Page.overrideSetting', {
  236. setting: 'PointerLockEnabled',
  237. value: !contextOptions.isMobile
  238. }));
  239. promises.push(session.send('Page.overrideSetting', {
  240. setting: 'InputTypeMonthEnabled',
  241. value: contextOptions.isMobile
  242. }));
  243. promises.push(session.send('Page.overrideSetting', {
  244. setting: 'InputTypeWeekEnabled',
  245. value: contextOptions.isMobile
  246. }));
  247. await Promise.all(promises);
  248. }
  249. _onDidCommitProvisionalTarget(event) {
  250. const {
  251. oldTargetId,
  252. newTargetId
  253. } = event;
  254. (0, _utils.assert)(this._provisionalPage);
  255. (0, _utils.assert)(this._provisionalPage._session.sessionId === newTargetId, 'Unknown new target: ' + newTargetId);
  256. (0, _utils.assert)(this._session.sessionId === oldTargetId, 'Unknown old target: ' + oldTargetId);
  257. const newSession = this._provisionalPage._session;
  258. this._provisionalPage.commit();
  259. this._provisionalPage.dispose();
  260. this._provisionalPage = null;
  261. this._setSession(newSession);
  262. }
  263. _onTargetDestroyed(event) {
  264. const {
  265. targetId,
  266. crashed
  267. } = event;
  268. if (this._provisionalPage && this._provisionalPage._session.sessionId === targetId) {
  269. this._provisionalPage._session.dispose();
  270. this._provisionalPage.dispose();
  271. this._provisionalPage = null;
  272. } else if (this._session.sessionId === targetId) {
  273. this._session.dispose();
  274. _eventsHelper.eventsHelper.removeEventListeners(this._sessionListeners);
  275. if (crashed) {
  276. this._session.markAsCrashed();
  277. this._page._didCrash();
  278. }
  279. }
  280. }
  281. didClose() {
  282. this._pageProxySession.dispose();
  283. _eventsHelper.eventsHelper.removeEventListeners(this._sessionListeners);
  284. _eventsHelper.eventsHelper.removeEventListeners(this._eventListeners);
  285. if (this._session) this._session.dispose();
  286. if (this._provisionalPage) {
  287. this._provisionalPage._session.dispose();
  288. this._provisionalPage.dispose();
  289. this._provisionalPage = null;
  290. }
  291. this._firstNonInitialNavigationCommittedReject(new _errors.TargetClosedError());
  292. this._page._didClose();
  293. }
  294. dispatchMessageToSession(message) {
  295. this._pageProxySession.dispatchMessage(message);
  296. }
  297. handleProvisionalLoadFailed(event) {
  298. if (!this._initializedPage) {
  299. this._firstNonInitialNavigationCommittedReject(new Error('Initial load failed'));
  300. return;
  301. }
  302. if (!this._provisionalPage) return;
  303. let errorText = event.error;
  304. if (errorText.includes('cancelled')) errorText += '; maybe frame was detached?';
  305. this._page._frameManager.frameAbortedNavigation(this._page.mainFrame()._id, errorText, event.loaderId);
  306. }
  307. handleWindowOpen(event) {
  308. (0, _utils.debugAssert)(!this._nextWindowOpenPopupFeatures);
  309. this._nextWindowOpenPopupFeatures = event.windowFeatures;
  310. }
  311. async pageOrError() {
  312. return this._pagePromise;
  313. }
  314. async _onTargetCreated(event) {
  315. const {
  316. targetInfo
  317. } = event;
  318. const session = new _wkConnection.WKSession(this._pageProxySession.connection, targetInfo.targetId, message => {
  319. this._pageProxySession.send('Target.sendMessageToTarget', {
  320. message: JSON.stringify(message),
  321. targetId: targetInfo.targetId
  322. }).catch(e => {
  323. session.dispatchMessage({
  324. id: message.id,
  325. error: {
  326. message: e.message
  327. }
  328. });
  329. });
  330. });
  331. (0, _utils.assert)(targetInfo.type === 'page', 'Only page targets are expected in WebKit, received: ' + targetInfo.type);
  332. if (!targetInfo.isProvisional) {
  333. (0, _utils.assert)(!this._initializedPage);
  334. let pageOrError;
  335. try {
  336. this._setSession(session);
  337. await Promise.all([this._initializePageProxySession(), this._initializeSession(session, false, ({
  338. frameTree
  339. }) => this._handleFrameTree(frameTree))]);
  340. pageOrError = this._page;
  341. } catch (e) {
  342. pageOrError = e;
  343. }
  344. if (targetInfo.isPaused) this._pageProxySession.sendMayFail('Target.resume', {
  345. targetId: targetInfo.targetId
  346. });
  347. if (pageOrError instanceof _page.Page && this._page.mainFrame().url() === '') {
  348. try {
  349. // Initial empty page has an empty url. We should wait until the first real url has been loaded,
  350. // even if that url is about:blank. This is especially important for popups, where we need the
  351. // actual url before interacting with it.
  352. await this._firstNonInitialNavigationCommittedPromise;
  353. } catch (e) {
  354. pageOrError = e;
  355. }
  356. } else {
  357. // Avoid rejection on disconnect.
  358. this._firstNonInitialNavigationCommittedPromise.catch(() => {});
  359. }
  360. await this._page.initOpener(this._opener);
  361. // Note: it is important to call |reportAsNew| before resolving pageOrError promise,
  362. // so that anyone who awaits pageOrError got a ready and reported page.
  363. this._initializedPage = pageOrError instanceof _page.Page ? pageOrError : null;
  364. this._page.reportAsNew(pageOrError instanceof _page.Page ? undefined : pageOrError);
  365. this._pagePromise.resolve(pageOrError);
  366. } else {
  367. (0, _utils.assert)(targetInfo.isProvisional);
  368. (0, _utils.assert)(!this._provisionalPage);
  369. this._provisionalPage = new _wkProvisionalPage.WKProvisionalPage(session, this);
  370. if (targetInfo.isPaused) {
  371. this._provisionalPage.initializationPromise.then(() => {
  372. this._pageProxySession.sendMayFail('Target.resume', {
  373. targetId: targetInfo.targetId
  374. });
  375. });
  376. }
  377. }
  378. }
  379. _onDispatchMessageFromTarget(event) {
  380. const {
  381. targetId,
  382. message
  383. } = event;
  384. if (this._provisionalPage && this._provisionalPage._session.sessionId === targetId) this._provisionalPage._session.dispatchMessage(JSON.parse(message));else if (this._session.sessionId === targetId) this._session.dispatchMessage(JSON.parse(message));else throw new Error('Unknown target: ' + targetId);
  385. }
  386. _addSessionListeners() {
  387. this._sessionListeners = [_eventsHelper.eventsHelper.addEventListener(this._session, 'Page.frameNavigated', event => this._onFrameNavigated(event.frame, false)), _eventsHelper.eventsHelper.addEventListener(this._session, 'Page.navigatedWithinDocument', event => this._onFrameNavigatedWithinDocument(event.frameId, event.url)), _eventsHelper.eventsHelper.addEventListener(this._session, 'Page.frameAttached', event => this._onFrameAttached(event.frameId, event.parentFrameId)), _eventsHelper.eventsHelper.addEventListener(this._session, 'Page.frameDetached', event => this._onFrameDetached(event.frameId)), _eventsHelper.eventsHelper.addEventListener(this._session, 'Page.willCheckNavigationPolicy', event => this._onWillCheckNavigationPolicy(event.frameId)), _eventsHelper.eventsHelper.addEventListener(this._session, 'Page.didCheckNavigationPolicy', event => this._onDidCheckNavigationPolicy(event.frameId, event.cancel)), _eventsHelper.eventsHelper.addEventListener(this._session, 'Page.frameScheduledNavigation', event => this._onFrameScheduledNavigation(event.frameId, event.delay, event.targetIsCurrentFrame)), _eventsHelper.eventsHelper.addEventListener(this._session, 'Page.loadEventFired', event => this._page._frameManager.frameLifecycleEvent(event.frameId, 'load')), _eventsHelper.eventsHelper.addEventListener(this._session, 'Page.domContentEventFired', event => this._page._frameManager.frameLifecycleEvent(event.frameId, 'domcontentloaded')), _eventsHelper.eventsHelper.addEventListener(this._session, 'Runtime.executionContextCreated', event => this._onExecutionContextCreated(event.context)), _eventsHelper.eventsHelper.addEventListener(this._session, 'Runtime.bindingCalled', event => this._onBindingCalled(event.contextId, event.argument)), _eventsHelper.eventsHelper.addEventListener(this._session, 'Console.messageAdded', event => this._onConsoleMessage(event)), _eventsHelper.eventsHelper.addEventListener(this._session, 'Console.messageRepeatCountUpdated', event => this._onConsoleRepeatCountUpdated(event)), _eventsHelper.eventsHelper.addEventListener(this._pageProxySession, 'Dialog.javascriptDialogOpening', event => this._onDialog(event)), _eventsHelper.eventsHelper.addEventListener(this._session, 'Page.fileChooserOpened', event => this._onFileChooserOpened(event)), _eventsHelper.eventsHelper.addEventListener(this._session, 'Network.requestWillBeSent', e => this._onRequestWillBeSent(this._session, e)), _eventsHelper.eventsHelper.addEventListener(this._session, 'Network.requestIntercepted', e => this._onRequestIntercepted(this._session, e)), _eventsHelper.eventsHelper.addEventListener(this._session, 'Network.responseReceived', e => this._onResponseReceived(this._session, e)), _eventsHelper.eventsHelper.addEventListener(this._session, 'Network.loadingFinished', e => this._onLoadingFinished(e)), _eventsHelper.eventsHelper.addEventListener(this._session, 'Network.loadingFailed', e => this._onLoadingFailed(this._session, e)), _eventsHelper.eventsHelper.addEventListener(this._session, 'Network.webSocketCreated', e => this._page._frameManager.onWebSocketCreated(e.requestId, e.url)), _eventsHelper.eventsHelper.addEventListener(this._session, 'Network.webSocketWillSendHandshakeRequest', e => this._page._frameManager.onWebSocketRequest(e.requestId)), _eventsHelper.eventsHelper.addEventListener(this._session, 'Network.webSocketHandshakeResponseReceived', e => this._page._frameManager.onWebSocketResponse(e.requestId, e.response.status, e.response.statusText)), _eventsHelper.eventsHelper.addEventListener(this._session, 'Network.webSocketFrameSent', e => e.response.payloadData && this._page._frameManager.onWebSocketFrameSent(e.requestId, e.response.opcode, e.response.payloadData)), _eventsHelper.eventsHelper.addEventListener(this._session, 'Network.webSocketFrameReceived', e => e.response.payloadData && this._page._frameManager.webSocketFrameReceived(e.requestId, e.response.opcode, e.response.payloadData)), _eventsHelper.eventsHelper.addEventListener(this._session, 'Network.webSocketClosed', e => this._page._frameManager.webSocketClosed(e.requestId)), _eventsHelper.eventsHelper.addEventListener(this._session, 'Network.webSocketFrameError', e => this._page._frameManager.webSocketError(e.requestId, e.errorMessage))];
  388. }
  389. async _updateState(method, params) {
  390. await this._forAllSessions(session => session.send(method, params).then());
  391. }
  392. async _forAllSessions(callback) {
  393. const sessions = [this._session];
  394. // If the state changes during provisional load, push it to the provisional page
  395. // as well to always be in sync with the backend.
  396. if (this._provisionalPage) sessions.push(this._provisionalPage._session);
  397. await Promise.all(sessions.map(session => callback(session).catch(e => {})));
  398. }
  399. _onWillCheckNavigationPolicy(frameId) {
  400. // It may happen that new policy check occurs while there is an ongoing
  401. // provisional load, in this case it should be safe to ignore it as it will
  402. // either:
  403. // - end up canceled, e.g. ctrl+click opening link in new tab, having no effect
  404. // on this page
  405. // - start new provisional load which we will miss in our signal trackers but
  406. // we certainly won't hang waiting for it to finish and there is high chance
  407. // that the current provisional page will commit navigation canceling the new
  408. // one.
  409. if (this._provisionalPage) return;
  410. this._page._frameManager.frameRequestedNavigation(frameId);
  411. }
  412. _onDidCheckNavigationPolicy(frameId, cancel) {
  413. if (!cancel) return;
  414. // This is a cross-process navigation that is canceled in the original page and continues in
  415. // the provisional page. Bail out as we are tracking it.
  416. if (this._provisionalPage) return;
  417. this._page._frameManager.frameAbortedNavigation(frameId, 'Navigation canceled by policy check');
  418. }
  419. _onFrameScheduledNavigation(frameId, delay, targetIsCurrentFrame) {
  420. if (targetIsCurrentFrame) this._page._frameManager.frameRequestedNavigation(frameId);
  421. }
  422. _handleFrameTree(frameTree) {
  423. this._onFrameAttached(frameTree.frame.id, frameTree.frame.parentId || null);
  424. this._onFrameNavigated(frameTree.frame, true);
  425. this._page._frameManager.frameLifecycleEvent(frameTree.frame.id, 'domcontentloaded');
  426. this._page._frameManager.frameLifecycleEvent(frameTree.frame.id, 'load');
  427. if (!frameTree.childFrames) return;
  428. for (const child of frameTree.childFrames) this._handleFrameTree(child);
  429. }
  430. _onFrameAttached(frameId, parentFrameId) {
  431. return this._page._frameManager.frameAttached(frameId, parentFrameId);
  432. }
  433. _onFrameNavigated(framePayload, initial) {
  434. const frame = this._page._frameManager.frame(framePayload.id);
  435. (0, _utils.assert)(frame);
  436. this._removeContextsForFrame(frame, true);
  437. if (!framePayload.parentId) this._workers.clear();
  438. this._page._frameManager.frameCommittedNewDocumentNavigation(framePayload.id, framePayload.url, framePayload.name || '', framePayload.loaderId, initial);
  439. if (!initial) this._firstNonInitialNavigationCommittedFulfill();
  440. }
  441. _onFrameNavigatedWithinDocument(frameId, url) {
  442. this._page._frameManager.frameCommittedSameDocumentNavigation(frameId, url);
  443. }
  444. _onFrameDetached(frameId) {
  445. this._page._frameManager.frameDetached(frameId);
  446. }
  447. _removeContextsForFrame(frame, notifyFrame) {
  448. for (const [contextId, context] of this._contextIdToContext) {
  449. if (context.frame === frame) {
  450. this._contextIdToContext.delete(contextId);
  451. if (notifyFrame) frame._contextDestroyed(context);
  452. }
  453. }
  454. }
  455. _onExecutionContextCreated(contextPayload) {
  456. if (this._contextIdToContext.has(contextPayload.id)) return;
  457. const frame = this._page._frameManager.frame(contextPayload.frameId);
  458. if (!frame) return;
  459. const delegate = new _wkExecutionContext.WKExecutionContext(this._session, contextPayload.id);
  460. let worldName = null;
  461. if (contextPayload.type === 'normal') worldName = 'main';else if (contextPayload.type === 'user' && contextPayload.name === UTILITY_WORLD_NAME) worldName = 'utility';
  462. const context = new dom.FrameExecutionContext(delegate, frame, worldName);
  463. context[contextDelegateSymbol] = delegate;
  464. if (worldName) frame._contextCreated(worldName, context);
  465. this._contextIdToContext.set(contextPayload.id, context);
  466. }
  467. async _onBindingCalled(contextId, argument) {
  468. const pageOrError = await this.pageOrError();
  469. if (!(pageOrError instanceof Error)) {
  470. const context = this._contextIdToContext.get(contextId);
  471. if (context) await this._page._onBindingCalled(argument, context);
  472. }
  473. }
  474. async navigateFrame(frame, url, referrer) {
  475. if (this._pageProxySession.isDisposed()) throw new _errors.TargetClosedError();
  476. const pageProxyId = this._pageProxySession.sessionId;
  477. const result = await this._pageProxySession.connection.browserSession.send('Playwright.navigate', {
  478. url,
  479. pageProxyId,
  480. frameId: frame._id,
  481. referrer
  482. });
  483. return {
  484. newDocumentId: result.loaderId
  485. };
  486. }
  487. _onConsoleMessage(event) {
  488. // Note: do no introduce await in this function, otherwise we lose the ordering.
  489. // For example, frame.setContent relies on this.
  490. const {
  491. type,
  492. level,
  493. text,
  494. parameters,
  495. url,
  496. line: lineNumber,
  497. column: columnNumber,
  498. source
  499. } = event.message;
  500. if (level === 'error' && source === 'javascript') {
  501. const {
  502. name,
  503. message
  504. } = (0, _stackTrace.splitErrorMessage)(text);
  505. let stack;
  506. if (event.message.stackTrace) {
  507. stack = text + '\n' + event.message.stackTrace.callFrames.map(callFrame => {
  508. return ` at ${callFrame.functionName || 'unknown'} (${callFrame.url}:${callFrame.lineNumber}:${callFrame.columnNumber})`;
  509. }).join('\n');
  510. } else {
  511. stack = '';
  512. }
  513. this._lastConsoleMessage = null;
  514. const error = new Error(message);
  515. error.stack = stack;
  516. error.name = name;
  517. this._page.emitOnContextOnceInitialized(_browserContext.BrowserContext.Events.PageError, error, this._page);
  518. return;
  519. }
  520. let derivedType = type || '';
  521. if (type === 'log') derivedType = level;else if (type === 'timing') derivedType = 'timeEnd';
  522. const handles = [];
  523. for (const p of parameters || []) {
  524. let context;
  525. if (p.objectId) {
  526. const objectId = JSON.parse(p.objectId);
  527. context = this._contextIdToContext.get(objectId.injectedScriptId);
  528. } else {
  529. // Pick any context if the parameter is a value.
  530. context = [...this._contextIdToContext.values()].find(c => c.frame === this._page.mainFrame());
  531. }
  532. if (!context) return;
  533. handles.push(context.createHandle(p));
  534. }
  535. this._lastConsoleMessage = {
  536. derivedType,
  537. text,
  538. handles,
  539. count: 0,
  540. location: {
  541. url: url || '',
  542. lineNumber: (lineNumber || 1) - 1,
  543. columnNumber: (columnNumber || 1) - 1
  544. }
  545. };
  546. this._onConsoleRepeatCountUpdated({
  547. count: 1
  548. });
  549. }
  550. _onConsoleRepeatCountUpdated(event) {
  551. if (this._lastConsoleMessage) {
  552. const {
  553. derivedType,
  554. text,
  555. handles,
  556. count,
  557. location
  558. } = this._lastConsoleMessage;
  559. for (let i = count; i < event.count; ++i) this._page._addConsoleMessage(derivedType, handles, location, handles.length ? undefined : text);
  560. this._lastConsoleMessage.count = event.count;
  561. }
  562. }
  563. _onDialog(event) {
  564. this._page.emitOnContext(_browserContext.BrowserContext.Events.Dialog, new dialog.Dialog(this._page, event.type, event.message, async (accept, promptText) => {
  565. await this._pageProxySession.send('Dialog.handleJavaScriptDialog', {
  566. accept,
  567. promptText
  568. });
  569. }, event.defaultPrompt));
  570. }
  571. async _onFileChooserOpened(event) {
  572. let handle;
  573. try {
  574. const context = await this._page._frameManager.frame(event.frameId)._mainContext();
  575. handle = context.createHandle(event.element).asElement();
  576. } catch (e) {
  577. // During async processing, frame/context may go away. We should not throw.
  578. return;
  579. }
  580. await this._page._onFileChooserOpened(handle);
  581. }
  582. static async _setEmulateMedia(session, mediaType, colorScheme, reducedMotion, forcedColors) {
  583. const promises = [];
  584. promises.push(session.send('Page.setEmulatedMedia', {
  585. media: mediaType === 'no-override' ? '' : mediaType
  586. }));
  587. let appearance = undefined;
  588. switch (colorScheme) {
  589. case 'light':
  590. appearance = 'Light';
  591. break;
  592. case 'dark':
  593. appearance = 'Dark';
  594. break;
  595. case 'no-override':
  596. appearance = undefined;
  597. break;
  598. }
  599. promises.push(session.send('Page.overrideUserPreference', {
  600. name: 'PrefersColorScheme',
  601. value: appearance
  602. }));
  603. let reducedMotionWk = undefined;
  604. switch (reducedMotion) {
  605. case 'reduce':
  606. reducedMotionWk = 'Reduce';
  607. break;
  608. case 'no-preference':
  609. reducedMotionWk = 'NoPreference';
  610. break;
  611. case 'no-override':
  612. reducedMotionWk = undefined;
  613. break;
  614. }
  615. promises.push(session.send('Page.overrideUserPreference', {
  616. name: 'PrefersReducedMotion',
  617. value: reducedMotionWk
  618. }));
  619. let forcedColorsWk = undefined;
  620. switch (forcedColors) {
  621. case 'active':
  622. forcedColorsWk = 'Active';
  623. break;
  624. case 'none':
  625. forcedColorsWk = 'None';
  626. break;
  627. case 'no-override':
  628. forcedColorsWk = undefined;
  629. break;
  630. }
  631. promises.push(session.send('Page.setForcedColors', {
  632. forcedColors: forcedColorsWk
  633. }));
  634. await Promise.all(promises);
  635. }
  636. async updateExtraHTTPHeaders() {
  637. await this._updateState('Network.setExtraHTTPHeaders', {
  638. headers: (0, _utils.headersArrayToObject)(this._calculateExtraHTTPHeaders(), false /* lowerCase */)
  639. });
  640. }
  641. _calculateExtraHTTPHeaders() {
  642. const locale = this._browserContext._options.locale;
  643. const headers = network.mergeHeaders([this._browserContext._options.extraHTTPHeaders, this._page.extraHTTPHeaders(), locale ? network.singleHeader('Accept-Language', locale) : undefined]);
  644. return headers;
  645. }
  646. async updateEmulateMedia() {
  647. const emulatedMedia = this._page.emulatedMedia();
  648. const colorScheme = emulatedMedia.colorScheme;
  649. const reducedMotion = emulatedMedia.reducedMotion;
  650. const forcedColors = emulatedMedia.forcedColors;
  651. await this._forAllSessions(session => WKPage._setEmulateMedia(session, emulatedMedia.media, colorScheme, reducedMotion, forcedColors));
  652. }
  653. async updateEmulatedViewportSize() {
  654. this._browserContext._validateEmulatedViewport(this._page.viewportSize());
  655. await this._updateViewport();
  656. }
  657. async updateUserAgent() {
  658. const contextOptions = this._browserContext._options;
  659. this._updateState('Page.overrideUserAgent', {
  660. value: contextOptions.userAgent
  661. });
  662. }
  663. async bringToFront() {
  664. this._pageProxySession.send('Target.activate', {
  665. targetId: this._session.sessionId
  666. });
  667. }
  668. async _updateViewport() {
  669. const options = this._browserContext._options;
  670. const deviceSize = this._page.emulatedSize();
  671. if (deviceSize === null) return;
  672. const viewportSize = deviceSize.viewport;
  673. const screenSize = deviceSize.screen;
  674. const promises = [this._pageProxySession.send('Emulation.setDeviceMetricsOverride', {
  675. width: viewportSize.width,
  676. height: viewportSize.height,
  677. fixedLayout: !!options.isMobile,
  678. deviceScaleFactor: options.deviceScaleFactor || 1
  679. }), this._session.send('Page.setScreenSizeOverride', {
  680. width: screenSize.width,
  681. height: screenSize.height
  682. })];
  683. if (options.isMobile) {
  684. const angle = viewportSize.width > viewportSize.height ? 90 : 0;
  685. promises.push(this._session.send('Page.setOrientationOverride', {
  686. angle
  687. }));
  688. }
  689. await Promise.all(promises);
  690. }
  691. async updateRequestInterception() {
  692. const enabled = this._page.needsRequestInterception();
  693. await Promise.all([this._updateState('Network.setInterceptionEnabled', {
  694. enabled
  695. }), this._updateState('Network.setResourceCachingDisabled', {
  696. disabled: enabled
  697. }), this._updateState('Network.addInterception', {
  698. url: '.*',
  699. stage: 'request',
  700. isRegex: true
  701. })]);
  702. }
  703. async updateOffline() {
  704. await this._updateState('Network.setEmulateOfflineState', {
  705. offline: !!this._browserContext._options.offline
  706. });
  707. }
  708. async updateHttpCredentials() {
  709. const credentials = this._browserContext._options.httpCredentials || {
  710. username: '',
  711. password: '',
  712. origin: ''
  713. };
  714. await this._pageProxySession.send('Emulation.setAuthCredentials', {
  715. username: credentials.username,
  716. password: credentials.password,
  717. origin: credentials.origin
  718. });
  719. }
  720. async updateFileChooserInterception() {
  721. const enabled = this._page.fileChooserIntercepted();
  722. await this._session.send('Page.setInterceptFileChooserDialog', {
  723. enabled
  724. }).catch(() => {}); // target can be closed.
  725. }
  726. async reload() {
  727. await this._session.send('Page.reload');
  728. }
  729. goBack() {
  730. return this._session.send('Page.goBack').then(() => true).catch(error => {
  731. if (error instanceof Error && error.message.includes(`Protocol error (Page.goBack): Failed to go`)) return false;
  732. throw error;
  733. });
  734. }
  735. goForward() {
  736. return this._session.send('Page.goForward').then(() => true).catch(error => {
  737. if (error instanceof Error && error.message.includes(`Protocol error (Page.goForward): Failed to go`)) return false;
  738. throw error;
  739. });
  740. }
  741. async exposeBinding(binding) {
  742. this._session.send('Runtime.addBinding', {
  743. name: binding.name
  744. });
  745. await this._updateBootstrapScript();
  746. await Promise.all(this._page.frames().map(frame => frame.evaluateExpression(binding.source).catch(e => {})));
  747. }
  748. async removeExposedBindings() {
  749. await this._updateBootstrapScript();
  750. }
  751. async addInitScript(script) {
  752. await this._updateBootstrapScript();
  753. }
  754. async removeInitScripts() {
  755. await this._updateBootstrapScript();
  756. }
  757. _calculateBootstrapScript() {
  758. const scripts = [];
  759. if (!this._page.context()._options.isMobile) {
  760. scripts.push('delete window.orientation');
  761. scripts.push('delete window.ondevicemotion');
  762. scripts.push('delete window.ondeviceorientation');
  763. }
  764. scripts.push('if (!window.safari) window.safari = {};');
  765. scripts.push('if (!window.GestureEvent) window.GestureEvent = function GestureEvent() {};');
  766. for (const binding of this._page.allBindings()) scripts.push(binding.source);
  767. scripts.push(...this._browserContext.initScripts);
  768. scripts.push(...this._page.initScripts);
  769. return scripts.join(';\n');
  770. }
  771. async _updateBootstrapScript() {
  772. await this._updateState('Page.setBootstrapScript', {
  773. source: this._calculateBootstrapScript()
  774. });
  775. }
  776. async closePage(runBeforeUnload) {
  777. await this._stopVideo();
  778. await this._pageProxySession.sendMayFail('Target.close', {
  779. targetId: this._session.sessionId,
  780. runBeforeUnload
  781. });
  782. }
  783. async setBackgroundColor(color) {
  784. await this._session.send('Page.setDefaultBackgroundColorOverride', {
  785. color
  786. });
  787. }
  788. _toolbarHeight() {
  789. var _this$_page$_browserC;
  790. if ((_this$_page$_browserC = this._page._browserContext._browser) !== null && _this$_page$_browserC !== void 0 && _this$_page$_browserC.options.headful) return _hostPlatform.hostPlatform === 'mac10.15' ? 55 : 59;
  791. return 0;
  792. }
  793. async _startVideo(options) {
  794. (0, _utils.assert)(!this._recordingVideoFile);
  795. const {
  796. screencastId
  797. } = await this._pageProxySession.send('Screencast.startVideo', {
  798. file: options.outputFile,
  799. width: options.width,
  800. height: options.height,
  801. toolbarHeight: this._toolbarHeight()
  802. });
  803. this._recordingVideoFile = options.outputFile;
  804. this._browserContext._browser._videoStarted(this._browserContext, screencastId, options.outputFile, this.pageOrError());
  805. }
  806. async _stopVideo() {
  807. if (!this._recordingVideoFile) return;
  808. await this._pageProxySession.sendMayFail('Screencast.stopVideo');
  809. this._recordingVideoFile = null;
  810. }
  811. validateScreenshotDimension(side, omitDeviceScaleFactor) {
  812. // Cairo based implementations (Linux and Windows) have hard limit of 32767
  813. // (see https://github.com/microsoft/playwright/issues/16727).
  814. if (process.platform === 'darwin') return;
  815. if (!omitDeviceScaleFactor && this._page._browserContext._options.deviceScaleFactor) side = Math.ceil(side * this._page._browserContext._options.deviceScaleFactor);
  816. if (side > 32767) throw new Error('Cannot take screenshot larger than 32767 pixels on any dimension');
  817. }
  818. async takeScreenshot(progress, format, documentRect, viewportRect, quality, fitsViewport, scale) {
  819. const rect = documentRect || viewportRect;
  820. const omitDeviceScaleFactor = scale === 'css';
  821. this.validateScreenshotDimension(rect.width, omitDeviceScaleFactor);
  822. this.validateScreenshotDimension(rect.height, omitDeviceScaleFactor);
  823. const result = await this._session.send('Page.snapshotRect', {
  824. ...rect,
  825. coordinateSystem: documentRect ? 'Page' : 'Viewport',
  826. omitDeviceScaleFactor
  827. });
  828. const prefix = 'data:image/png;base64,';
  829. let buffer = Buffer.from(result.dataURL.substr(prefix.length), 'base64');
  830. if (format === 'jpeg') buffer = _utilsBundle.jpegjs.encode(_utilsBundle.PNG.sync.read(buffer), quality).data;
  831. return buffer;
  832. }
  833. async getContentFrame(handle) {
  834. const nodeInfo = await this._session.send('DOM.describeNode', {
  835. objectId: handle._objectId
  836. });
  837. if (!nodeInfo.contentFrameId) return null;
  838. return this._page._frameManager.frame(nodeInfo.contentFrameId);
  839. }
  840. async getOwnerFrame(handle) {
  841. if (!handle._objectId) return null;
  842. const nodeInfo = await this._session.send('DOM.describeNode', {
  843. objectId: handle._objectId
  844. });
  845. return nodeInfo.ownerFrameId || null;
  846. }
  847. isElementHandle(remoteObject) {
  848. return remoteObject.subtype === 'node';
  849. }
  850. async getBoundingBox(handle) {
  851. const quads = await this.getContentQuads(handle);
  852. if (!quads || !quads.length) return null;
  853. let minX = Infinity;
  854. let maxX = -Infinity;
  855. let minY = Infinity;
  856. let maxY = -Infinity;
  857. for (const quad of quads) {
  858. for (const point of quad) {
  859. minX = Math.min(minX, point.x);
  860. maxX = Math.max(maxX, point.x);
  861. minY = Math.min(minY, point.y);
  862. maxY = Math.max(maxY, point.y);
  863. }
  864. }
  865. return {
  866. x: minX,
  867. y: minY,
  868. width: maxX - minX,
  869. height: maxY - minY
  870. };
  871. }
  872. async scrollRectIntoViewIfNeeded(handle, rect) {
  873. return await this._session.send('DOM.scrollIntoViewIfNeeded', {
  874. objectId: handle._objectId,
  875. rect
  876. }).then(() => 'done').catch(e => {
  877. if (e instanceof Error && e.message.includes('Node does not have a layout object')) return 'error:notvisible';
  878. if (e instanceof Error && e.message.includes('Node is detached from document')) return 'error:notconnected';
  879. throw e;
  880. });
  881. }
  882. async setScreencastOptions(options) {
  883. if (options) {
  884. const so = {
  885. ...options,
  886. toolbarHeight: this._toolbarHeight()
  887. };
  888. const {
  889. generation
  890. } = await this._pageProxySession.send('Screencast.startScreencast', so);
  891. this._screencastGeneration = generation;
  892. } else {
  893. await this._pageProxySession.send('Screencast.stopScreencast');
  894. }
  895. }
  896. _onScreencastFrame(event) {
  897. const generation = this._screencastGeneration;
  898. this._page.throttleScreencastFrameAck(() => {
  899. this._pageProxySession.send('Screencast.screencastFrameAck', {
  900. generation
  901. }).catch(e => _debugLogger.debugLogger.log('error', e));
  902. });
  903. const buffer = Buffer.from(event.data, 'base64');
  904. this._page.emit(_page.Page.Events.ScreencastFrame, {
  905. buffer,
  906. width: event.deviceWidth,
  907. height: event.deviceHeight
  908. });
  909. }
  910. rafCountForStablePosition() {
  911. return process.platform === 'win32' ? 5 : 1;
  912. }
  913. async getContentQuads(handle) {
  914. const result = await this._session.sendMayFail('DOM.getContentQuads', {
  915. objectId: handle._objectId
  916. });
  917. if (!result) return null;
  918. return result.quads.map(quad => [{
  919. x: quad[0],
  920. y: quad[1]
  921. }, {
  922. x: quad[2],
  923. y: quad[3]
  924. }, {
  925. x: quad[4],
  926. y: quad[5]
  927. }, {
  928. x: quad[6],
  929. y: quad[7]
  930. }]);
  931. }
  932. async setInputFiles(handle, files) {
  933. const objectId = handle._objectId;
  934. const protocolFiles = files.map(file => ({
  935. name: file.name,
  936. type: file.mimeType,
  937. data: file.buffer
  938. }));
  939. await this._session.send('DOM.setInputFiles', {
  940. objectId,
  941. files: protocolFiles
  942. });
  943. }
  944. async setInputFilePaths(progress, handle, paths) {
  945. const pageProxyId = this._pageProxySession.sessionId;
  946. const objectId = handle._objectId;
  947. await Promise.all([this._pageProxySession.connection.browserSession.send('Playwright.grantFileReadAccess', {
  948. pageProxyId,
  949. paths
  950. }), this._session.send('DOM.setInputFiles', {
  951. objectId,
  952. paths
  953. })]);
  954. }
  955. async adoptElementHandle(handle, to) {
  956. const result = await this._session.sendMayFail('DOM.resolveNode', {
  957. objectId: handle._objectId,
  958. executionContextId: to[contextDelegateSymbol]._contextId
  959. });
  960. if (!result || result.object.subtype === 'null') throw new Error(dom.kUnableToAdoptErrorMessage);
  961. return to.createHandle(result.object);
  962. }
  963. async getAccessibilityTree(needle) {
  964. return (0, _wkAccessibility.getAccessibilityTree)(this._session, needle);
  965. }
  966. async inputActionEpilogue() {}
  967. async resetForReuse() {}
  968. async getFrameElement(frame) {
  969. const parent = frame.parentFrame();
  970. if (!parent) throw new Error('Frame has been detached.');
  971. const context = await parent._mainContext();
  972. const result = await this._session.send('DOM.resolveNode', {
  973. frameId: frame._id,
  974. executionContextId: context[contextDelegateSymbol]._contextId
  975. });
  976. if (!result || result.object.subtype === 'null') throw new Error('Frame has been detached.');
  977. return context.createHandle(result.object);
  978. }
  979. _onRequestWillBeSent(session, event) {
  980. if (event.request.url.startsWith('data:')) return;
  981. // We do not support intercepting redirects.
  982. if (this._page.needsRequestInterception() && !event.redirectResponse) this._requestIdToRequestWillBeSentEvent.set(event.requestId, event);else this._onRequest(session, event, false);
  983. }
  984. _onRequest(session, event, intercepted) {
  985. let redirectedFrom = null;
  986. if (event.redirectResponse) {
  987. const request = this._requestIdToRequest.get(event.requestId);
  988. // If we connect late to the target, we could have missed the requestWillBeSent event.
  989. if (request) {
  990. this._handleRequestRedirect(request, event.redirectResponse, event.timestamp);
  991. redirectedFrom = request;
  992. }
  993. }
  994. const frame = redirectedFrom ? redirectedFrom.request.frame() : this._page._frameManager.frame(event.frameId);
  995. // sometimes we get stray network events for detached frames
  996. // TODO(einbinder) why?
  997. if (!frame) return;
  998. // TODO(einbinder) this will fail if we are an XHR document request
  999. const isNavigationRequest = event.type === 'Document';
  1000. const documentId = isNavigationRequest ? event.loaderId : undefined;
  1001. const request = new _wkInterceptableRequest.WKInterceptableRequest(session, frame, event, redirectedFrom, documentId);
  1002. let route;
  1003. if (intercepted) {
  1004. route = new _wkInterceptableRequest.WKRouteImpl(session, request._requestId);
  1005. // There is no point in waiting for the raw headers in Network.responseReceived when intercepting.
  1006. // Use provisional headers as raw headers, so that client can call allHeaders() from the route handler.
  1007. request.request.setRawRequestHeaders(null);
  1008. }
  1009. this._requestIdToRequest.set(event.requestId, request);
  1010. this._page._frameManager.requestStarted(request.request, route);
  1011. }
  1012. _handleRequestRedirect(request, responsePayload, timestamp) {
  1013. const response = request.createResponse(responsePayload);
  1014. response._securityDetailsFinished();
  1015. response._serverAddrFinished();
  1016. response.setResponseHeadersSize(null);
  1017. response.setEncodedBodySize(null);
  1018. response._requestFinished(responsePayload.timing ? _helper.helper.secondsToRoundishMillis(timestamp - request._timestamp) : -1);
  1019. this._requestIdToRequest.delete(request._requestId);
  1020. this._page._frameManager.requestReceivedResponse(response);
  1021. this._page._frameManager.reportRequestFinished(request.request, response);
  1022. }
  1023. _onRequestIntercepted(session, event) {
  1024. const requestWillBeSentEvent = this._requestIdToRequestWillBeSentEvent.get(event.requestId);
  1025. if (!requestWillBeSentEvent) {
  1026. // Intercepted, although we do not intend to allow interception.
  1027. // Just continue.
  1028. session.sendMayFail('Network.interceptWithRequest', {
  1029. requestId: event.requestId
  1030. });
  1031. return;
  1032. }
  1033. this._requestIdToRequestWillBeSentEvent.delete(event.requestId);
  1034. this._onRequest(session, requestWillBeSentEvent, true);
  1035. }
  1036. _onResponseReceived(session, event) {
  1037. const requestWillBeSentEvent = this._requestIdToRequestWillBeSentEvent.get(event.requestId);
  1038. if (requestWillBeSentEvent) {
  1039. this._requestIdToRequestWillBeSentEvent.delete(event.requestId);
  1040. // We received a response, so the request won't be intercepted (e.g. it was handled by a
  1041. // service worker and we don't intercept service workers).
  1042. this._onRequest(session, requestWillBeSentEvent, false);
  1043. }
  1044. const request = this._requestIdToRequest.get(event.requestId);
  1045. // FileUpload sends a response without a matching request.
  1046. if (!request) return;
  1047. this._requestIdToResponseReceivedPayloadEvent.set(request._requestId, event);
  1048. const response = request.createResponse(event.response);
  1049. this._page._frameManager.requestReceivedResponse(response);
  1050. if (response.status() === 204) {
  1051. this._onLoadingFailed(session, {
  1052. requestId: event.requestId,
  1053. errorText: 'Aborted: 204 No Content',
  1054. timestamp: event.timestamp
  1055. });
  1056. }
  1057. }
  1058. _onLoadingFinished(event) {
  1059. const request = this._requestIdToRequest.get(event.requestId);
  1060. // For certain requestIds we never receive requestWillBeSent event.
  1061. // @see https://crbug.com/750469
  1062. if (!request) return;
  1063. // Under certain conditions we never get the Network.responseReceived
  1064. // event from protocol. @see https://crbug.com/883475
  1065. const response = request.request._existingResponse();
  1066. if (response) {
  1067. var _event$metrics, _event$metrics2, _event$metrics2$secur, _responseReceivedPayl, _responseReceivedPayl2, _responseReceivedPayl3, _responseReceivedPayl4, _responseReceivedPayl5, _responseReceivedPayl6, _event$metrics3, _event$metrics$respon, _event$metrics4, _event$metrics$respon2, _event$metrics5;
  1068. const responseReceivedPayload = this._requestIdToResponseReceivedPayloadEvent.get(request._requestId);
  1069. response._serverAddrFinished(parseRemoteAddress(event === null || event === void 0 ? void 0 : (_event$metrics = event.metrics) === null || _event$metrics === void 0 ? void 0 : _event$metrics.remoteAddress));
  1070. response._securityDetailsFinished({
  1071. protocol: isLoadedSecurely(response.url(), response.timing()) ? (_event$metrics2 = event.metrics) === null || _event$metrics2 === void 0 ? void 0 : (_event$metrics2$secur = _event$metrics2.securityConnection) === null || _event$metrics2$secur === void 0 ? void 0 : _event$metrics2$secur.protocol : undefined,
  1072. subjectName: responseReceivedPayload === null || responseReceivedPayload === void 0 ? void 0 : (_responseReceivedPayl = responseReceivedPayload.response.security) === null || _responseReceivedPayl === void 0 ? void 0 : (_responseReceivedPayl2 = _responseReceivedPayl.certificate) === null || _responseReceivedPayl2 === void 0 ? void 0 : _responseReceivedPayl2.subject,
  1073. validFrom: responseReceivedPayload === null || responseReceivedPayload === void 0 ? void 0 : (_responseReceivedPayl3 = responseReceivedPayload.response.security) === null || _responseReceivedPayl3 === void 0 ? void 0 : (_responseReceivedPayl4 = _responseReceivedPayl3.certificate) === null || _responseReceivedPayl4 === void 0 ? void 0 : _responseReceivedPayl4.validFrom,
  1074. validTo: responseReceivedPayload === null || responseReceivedPayload === void 0 ? void 0 : (_responseReceivedPayl5 = responseReceivedPayload.response.security) === null || _responseReceivedPayl5 === void 0 ? void 0 : (_responseReceivedPayl6 = _responseReceivedPayl5.certificate) === null || _responseReceivedPayl6 === void 0 ? void 0 : _responseReceivedPayl6.validUntil
  1075. });
  1076. if ((_event$metrics3 = event.metrics) !== null && _event$metrics3 !== void 0 && _event$metrics3.protocol) response._setHttpVersion(event.metrics.protocol);
  1077. response.setEncodedBodySize((_event$metrics$respon = (_event$metrics4 = event.metrics) === null || _event$metrics4 === void 0 ? void 0 : _event$metrics4.responseBodyBytesReceived) !== null && _event$metrics$respon !== void 0 ? _event$metrics$respon : null);
  1078. response.setResponseHeadersSize((_event$metrics$respon2 = (_event$metrics5 = event.metrics) === null || _event$metrics5 === void 0 ? void 0 : _event$metrics5.responseHeaderBytesReceived) !== null && _event$metrics$respon2 !== void 0 ? _event$metrics$respon2 : null);
  1079. response._requestFinished(_helper.helper.secondsToRoundishMillis(event.timestamp - request._timestamp));
  1080. } else {
  1081. // Use provisional headers if we didn't have the response with raw headers.
  1082. request.request.setRawRequestHeaders(null);
  1083. }
  1084. this._requestIdToResponseReceivedPayloadEvent.delete(request._requestId);
  1085. this._requestIdToRequest.delete(request._requestId);
  1086. this._page._frameManager.reportRequestFinished(request.request, response);
  1087. }
  1088. _onLoadingFailed(session, event) {
  1089. const requestWillBeSentEvent = this._requestIdToRequestWillBeSentEvent.get(event.requestId);
  1090. if (requestWillBeSentEvent) {
  1091. this._requestIdToRequestWillBeSentEvent.delete(event.requestId);
  1092. // If loading failed, the request won't be intercepted (e.g. it was handled by a
  1093. // service worker and we don't intercept service workers).
  1094. this._onRequest(session, requestWillBeSentEvent, false);
  1095. }
  1096. const request = this._requestIdToRequest.get(event.requestId);
  1097. // For certain requestIds we never receive requestWillBeSent event.
  1098. // @see https://crbug.com/750469
  1099. if (!request) return;
  1100. const response = request.request._existingResponse();
  1101. if (response) {
  1102. response._serverAddrFinished();
  1103. response._securityDetailsFinished();
  1104. response.setResponseHeadersSize(null);
  1105. response.setEncodedBodySize(null);
  1106. response._requestFinished(_helper.helper.secondsToRoundishMillis(event.timestamp - request._timestamp));
  1107. } else {
  1108. // Use provisional headers if we didn't have the response with raw headers.
  1109. request.request.setRawRequestHeaders(null);
  1110. }
  1111. this._requestIdToRequest.delete(request._requestId);
  1112. request.request._setFailureText(event.errorText);
  1113. this._page._frameManager.requestFailed(request.request, event.errorText.includes('cancelled'));
  1114. }
  1115. async _grantPermissions(origin, permissions) {
  1116. const webPermissionToProtocol = new Map([['geolocation', 'geolocation'], ['clipboard-read', 'clipboard-read']]);
  1117. const filtered = permissions.map(permission => {
  1118. const protocolPermission = webPermissionToProtocol.get(permission);
  1119. if (!protocolPermission) throw new Error('Unknown permission: ' + permission);
  1120. return protocolPermission;
  1121. });
  1122. await this._pageProxySession.send('Emulation.grantPermissions', {
  1123. origin,
  1124. permissions: filtered
  1125. });
  1126. }
  1127. async _clearPermissions() {
  1128. await this._pageProxySession.send('Emulation.resetPermissions', {});
  1129. }
  1130. shouldToggleStyleSheetToSyncAnimations() {
  1131. return true;
  1132. }
  1133. }
  1134. /**
  1135. * WebKit Remote Addresses look like:
  1136. *
  1137. * macOS:
  1138. * ::1.8911
  1139. * 2606:2800:220:1:248:1893:25c8:1946.443
  1140. * 127.0.0.1:8000
  1141. *
  1142. * ubuntu:
  1143. * ::1:8907
  1144. * 127.0.0.1:8000
  1145. *
  1146. * NB: They look IPv4 and IPv6's with ports but use an alternative notation.
  1147. */
  1148. exports.WKPage = WKPage;
  1149. function parseRemoteAddress(value) {
  1150. if (!value) return;
  1151. try {
  1152. const colon = value.lastIndexOf(':');
  1153. const dot = value.lastIndexOf('.');
  1154. if (dot < 0) {
  1155. // IPv6ish:port
  1156. return {
  1157. ipAddress: `[${value.slice(0, colon)}]`,
  1158. port: +value.slice(colon + 1)
  1159. };
  1160. }
  1161. if (colon > dot) {
  1162. // IPv4:port
  1163. const [address, port] = value.split(':');
  1164. return {
  1165. ipAddress: address,
  1166. port: +port
  1167. };
  1168. } else {
  1169. // IPv6ish.port
  1170. const [address, port] = value.split('.');
  1171. return {
  1172. ipAddress: `[${address}]`,
  1173. port: +port
  1174. };
  1175. }
  1176. } catch (_) {}
  1177. }
  1178. /**
  1179. * Adapted from Source/WebInspectorUI/UserInterface/Models/Resource.js in
  1180. * WebKit codebase.
  1181. */
  1182. function isLoadedSecurely(url, timing) {
  1183. try {
  1184. const u = new URL(url);
  1185. if (u.protocol !== 'https:' && u.protocol !== 'wss:' && u.protocol !== 'sftp:') return false;
  1186. if (timing.secureConnectionStart === -1 && timing.connectStart !== -1) return false;
  1187. return true;
  1188. } catch (_) {}
  1189. }
  1190. const contextDelegateSymbol = Symbol('delegate');