pageDispatcher.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.WorkerDispatcher = exports.PageDispatcher = exports.BindingCallDispatcher = void 0;
  6. var _page = require("../page");
  7. var _dispatcher = require("./dispatcher");
  8. var _errors = require("../errors");
  9. var _frameDispatcher = require("./frameDispatcher");
  10. var _networkDispatchers = require("./networkDispatchers");
  11. var _jsHandleDispatcher = require("./jsHandleDispatcher");
  12. var _elementHandlerDispatcher = require("./elementHandlerDispatcher");
  13. var _artifactDispatcher = require("./artifactDispatcher");
  14. var _utils = require("../../utils");
  15. /**
  16. * Copyright (c) Microsoft Corporation.
  17. *
  18. * Licensed under the Apache License, Version 2.0 (the 'License');
  19. * you may not use this file except in compliance with the License.
  20. * You may obtain a copy of the License at
  21. *
  22. * http://www.apache.org/licenses/LICENSE-2.0
  23. *
  24. * Unless required by applicable law or agreed to in writing, software
  25. * distributed under the License is distributed on an 'AS IS' BASIS,
  26. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  27. * See the License for the specific language governing permissions and
  28. * limitations under the License.
  29. */
  30. class PageDispatcher extends _dispatcher.Dispatcher {
  31. static from(parentScope, page) {
  32. return PageDispatcher.fromNullable(parentScope, page);
  33. }
  34. static fromNullable(parentScope, page) {
  35. if (!page) return undefined;
  36. const result = (0, _dispatcher.existingDispatcher)(page);
  37. return result || new PageDispatcher(parentScope, page);
  38. }
  39. constructor(parentScope, page) {
  40. // TODO: theoretically, there could be more than one frame already.
  41. // If we split pageCreated and pageReady, there should be no main frame during pageCreated.
  42. // We will reparent it to the page below using adopt.
  43. const mainFrame = _frameDispatcher.FrameDispatcher.from(parentScope, page.mainFrame());
  44. super(parentScope, page, 'Page', {
  45. mainFrame,
  46. viewportSize: page.viewportSize() || undefined,
  47. isClosed: page.isClosed(),
  48. opener: PageDispatcher.fromNullable(parentScope, page.opener())
  49. });
  50. this._type_EventTarget = true;
  51. this._type_Page = true;
  52. this._page = void 0;
  53. this._subscriptions = new Set();
  54. this.adopt(mainFrame);
  55. this._page = page;
  56. this.addObjectListener(_page.Page.Events.Close, () => {
  57. this._dispatchEvent('close');
  58. this._dispose();
  59. });
  60. this.addObjectListener(_page.Page.Events.Crash, () => this._dispatchEvent('crash'));
  61. this.addObjectListener(_page.Page.Events.Download, download => {
  62. // Artifact can outlive the page, so bind to the context scope.
  63. this._dispatchEvent('download', {
  64. url: download.url,
  65. suggestedFilename: download.suggestedFilename(),
  66. artifact: _artifactDispatcher.ArtifactDispatcher.from(parentScope, download.artifact)
  67. });
  68. });
  69. this.addObjectListener(_page.Page.Events.FileChooser, fileChooser => this._dispatchEvent('fileChooser', {
  70. element: _elementHandlerDispatcher.ElementHandleDispatcher.from(mainFrame, fileChooser.element()),
  71. isMultiple: fileChooser.isMultiple()
  72. }));
  73. this.addObjectListener(_page.Page.Events.FrameAttached, frame => this._onFrameAttached(frame));
  74. this.addObjectListener(_page.Page.Events.FrameDetached, frame => this._onFrameDetached(frame));
  75. this.addObjectListener(_page.Page.Events.WebSocket, webSocket => this._dispatchEvent('webSocket', {
  76. webSocket: new _networkDispatchers.WebSocketDispatcher(this, webSocket)
  77. }));
  78. this.addObjectListener(_page.Page.Events.Worker, worker => this._dispatchEvent('worker', {
  79. worker: new WorkerDispatcher(this, worker)
  80. }));
  81. this.addObjectListener(_page.Page.Events.Video, artifact => this._dispatchEvent('video', {
  82. artifact: _artifactDispatcher.ArtifactDispatcher.from(parentScope, artifact)
  83. }));
  84. if (page._video) this._dispatchEvent('video', {
  85. artifact: _artifactDispatcher.ArtifactDispatcher.from(this.parentScope(), page._video)
  86. });
  87. // Ensure client knows about all frames.
  88. const frames = page._frameManager.frames();
  89. for (let i = 1; i < frames.length; i++) this._onFrameAttached(frames[i]);
  90. }
  91. page() {
  92. return this._page;
  93. }
  94. async setDefaultNavigationTimeoutNoReply(params, metadata) {
  95. this._page.setDefaultNavigationTimeout(params.timeout);
  96. }
  97. async setDefaultTimeoutNoReply(params, metadata) {
  98. this._page.setDefaultTimeout(params.timeout);
  99. }
  100. async exposeBinding(params, metadata) {
  101. await this._page.exposeBinding(params.name, !!params.needsHandle, (source, ...args) => {
  102. // When reusing the context, we might have some bindings called late enough,
  103. // after context and page dispatchers have been disposed.
  104. if (this._disposed) return;
  105. const binding = new BindingCallDispatcher(this, params.name, !!params.needsHandle, source, args);
  106. this._dispatchEvent('bindingCall', {
  107. binding
  108. });
  109. return binding.promise();
  110. });
  111. }
  112. async setExtraHTTPHeaders(params, metadata) {
  113. await this._page.setExtraHTTPHeaders(params.headers);
  114. }
  115. async reload(params, metadata) {
  116. return {
  117. response: _networkDispatchers.ResponseDispatcher.fromNullable(this.parentScope(), await this._page.reload(metadata, params))
  118. };
  119. }
  120. async goBack(params, metadata) {
  121. return {
  122. response: _networkDispatchers.ResponseDispatcher.fromNullable(this.parentScope(), await this._page.goBack(metadata, params))
  123. };
  124. }
  125. async goForward(params, metadata) {
  126. return {
  127. response: _networkDispatchers.ResponseDispatcher.fromNullable(this.parentScope(), await this._page.goForward(metadata, params))
  128. };
  129. }
  130. async emulateMedia(params, metadata) {
  131. await this._page.emulateMedia({
  132. media: params.media,
  133. colorScheme: params.colorScheme,
  134. reducedMotion: params.reducedMotion,
  135. forcedColors: params.forcedColors
  136. });
  137. }
  138. async setViewportSize(params, metadata) {
  139. await this._page.setViewportSize(params.viewportSize);
  140. }
  141. async addInitScript(params, metadata) {
  142. await this._page.addInitScript(params.source);
  143. }
  144. async setNetworkInterceptionPatterns(params, metadata) {
  145. if (!params.patterns.length) {
  146. await this._page.setClientRequestInterceptor(undefined);
  147. return;
  148. }
  149. const urlMatchers = params.patterns.map(pattern => pattern.regexSource ? new RegExp(pattern.regexSource, pattern.regexFlags) : pattern.glob);
  150. await this._page.setClientRequestInterceptor((route, request) => {
  151. const matchesSome = urlMatchers.some(urlMatch => (0, _utils.urlMatches)(this._page._browserContext._options.baseURL, request.url(), urlMatch));
  152. if (!matchesSome) return false;
  153. this._dispatchEvent('route', {
  154. route: _networkDispatchers.RouteDispatcher.from(_networkDispatchers.RequestDispatcher.from(this.parentScope(), request), route)
  155. });
  156. return true;
  157. });
  158. }
  159. async expectScreenshot(params, metadata) {
  160. var _params$screenshotOpt, _params$comparatorOpt;
  161. const mask = (((_params$screenshotOpt = params.screenshotOptions) === null || _params$screenshotOpt === void 0 ? void 0 : _params$screenshotOpt.mask) || []).map(({
  162. frame,
  163. selector
  164. }) => ({
  165. frame: frame._object,
  166. selector
  167. }));
  168. const locator = params.locator ? {
  169. frame: params.locator.frame._object,
  170. selector: params.locator.selector
  171. } : undefined;
  172. return await this._page.expectScreenshot(metadata, {
  173. ...params,
  174. locator,
  175. comparatorOptions: {
  176. ...params.comparatorOptions,
  177. _comparator: (_params$comparatorOpt = params.comparatorOptions) === null || _params$comparatorOpt === void 0 ? void 0 : _params$comparatorOpt.comparator
  178. },
  179. screenshotOptions: {
  180. ...params.screenshotOptions,
  181. mask
  182. }
  183. });
  184. }
  185. async screenshot(params, metadata) {
  186. const mask = (params.mask || []).map(({
  187. frame,
  188. selector
  189. }) => ({
  190. frame: frame._object,
  191. selector
  192. }));
  193. return {
  194. binary: await this._page.screenshot(metadata, {
  195. ...params,
  196. mask
  197. })
  198. };
  199. }
  200. async close(params, metadata) {
  201. if (!params.runBeforeUnload) metadata.potentiallyClosesScope = true;
  202. await this._page.close(metadata, params);
  203. }
  204. async updateSubscription(params) {
  205. if (params.event === 'fileChooser') await this._page.setFileChooserIntercepted(params.enabled);
  206. if (params.enabled) this._subscriptions.add(params.event);else this._subscriptions.delete(params.event);
  207. }
  208. async keyboardDown(params, metadata) {
  209. await this._page.keyboard.down(params.key);
  210. }
  211. async keyboardUp(params, metadata) {
  212. await this._page.keyboard.up(params.key);
  213. }
  214. async keyboardInsertText(params, metadata) {
  215. await this._page.keyboard.insertText(params.text);
  216. }
  217. async keyboardType(params, metadata) {
  218. await this._page.keyboard.type(params.text, params);
  219. }
  220. async keyboardPress(params, metadata) {
  221. await this._page.keyboard.press(params.key, params);
  222. }
  223. async mouseMove(params, metadata) {
  224. await this._page.mouse.move(params.x, params.y, params, metadata);
  225. }
  226. async mouseDown(params, metadata) {
  227. await this._page.mouse.down(params, metadata);
  228. }
  229. async mouseUp(params, metadata) {
  230. await this._page.mouse.up(params, metadata);
  231. }
  232. async mouseClick(params, metadata) {
  233. await this._page.mouse.click(params.x, params.y, params, metadata);
  234. }
  235. async mouseWheel(params, metadata) {
  236. await this._page.mouse.wheel(params.deltaX, params.deltaY);
  237. }
  238. async touchscreenTap(params, metadata) {
  239. await this._page.touchscreen.tap(params.x, params.y, metadata);
  240. }
  241. async accessibilitySnapshot(params, metadata) {
  242. const rootAXNode = await this._page.accessibility.snapshot({
  243. interestingOnly: params.interestingOnly,
  244. root: params.root ? params.root._elementHandle : undefined
  245. });
  246. return {
  247. rootAXNode: rootAXNode || undefined
  248. };
  249. }
  250. async pdf(params, metadata) {
  251. if (!this._page.pdf) throw new Error('PDF generation is only supported for Headless Chromium');
  252. const buffer = await this._page.pdf(params);
  253. return {
  254. pdf: buffer
  255. };
  256. }
  257. async bringToFront(params, metadata) {
  258. await this._page.bringToFront();
  259. }
  260. async startJSCoverage(params, metadata) {
  261. const coverage = this._page.coverage;
  262. await coverage.startJSCoverage(params);
  263. }
  264. async stopJSCoverage(params, metadata) {
  265. const coverage = this._page.coverage;
  266. return await coverage.stopJSCoverage();
  267. }
  268. async startCSSCoverage(params, metadata) {
  269. const coverage = this._page.coverage;
  270. await coverage.startCSSCoverage(params);
  271. }
  272. async stopCSSCoverage(params, metadata) {
  273. const coverage = this._page.coverage;
  274. return await coverage.stopCSSCoverage();
  275. }
  276. _onFrameAttached(frame) {
  277. this._dispatchEvent('frameAttached', {
  278. frame: _frameDispatcher.FrameDispatcher.from(this.parentScope(), frame)
  279. });
  280. }
  281. _onFrameDetached(frame) {
  282. this._dispatchEvent('frameDetached', {
  283. frame: _frameDispatcher.FrameDispatcher.from(this.parentScope(), frame)
  284. });
  285. }
  286. _onDispose() {
  287. // Avoid protocol calls for the closed page.
  288. if (!this._page.isClosedOrClosingOrCrashed()) this._page.setClientRequestInterceptor(undefined).catch(() => {});
  289. }
  290. }
  291. exports.PageDispatcher = PageDispatcher;
  292. class WorkerDispatcher extends _dispatcher.Dispatcher {
  293. static fromNullable(scope, worker) {
  294. if (!worker) return undefined;
  295. const result = (0, _dispatcher.existingDispatcher)(worker);
  296. return result || new WorkerDispatcher(scope, worker);
  297. }
  298. constructor(scope, worker) {
  299. super(scope, worker, 'Worker', {
  300. url: worker.url()
  301. });
  302. this._type_Worker = true;
  303. this.addObjectListener(_page.Worker.Events.Close, () => this._dispatchEvent('close'));
  304. }
  305. async evaluateExpression(params, metadata) {
  306. return {
  307. value: (0, _jsHandleDispatcher.serializeResult)(await this._object.evaluateExpression(params.expression, params.isFunction, (0, _jsHandleDispatcher.parseArgument)(params.arg)))
  308. };
  309. }
  310. async evaluateExpressionHandle(params, metadata) {
  311. return {
  312. handle: _elementHandlerDispatcher.ElementHandleDispatcher.fromJSHandle(this, await this._object.evaluateExpressionHandle(params.expression, params.isFunction, (0, _jsHandleDispatcher.parseArgument)(params.arg)))
  313. };
  314. }
  315. }
  316. exports.WorkerDispatcher = WorkerDispatcher;
  317. class BindingCallDispatcher extends _dispatcher.Dispatcher {
  318. constructor(scope, name, needsHandle, source, args) {
  319. super(scope, {
  320. guid: 'bindingCall@' + (0, _utils.createGuid)()
  321. }, 'BindingCall', {
  322. frame: _frameDispatcher.FrameDispatcher.from(scope.parentScope(), source.frame),
  323. name,
  324. args: needsHandle ? undefined : args.map(_jsHandleDispatcher.serializeResult),
  325. handle: needsHandle ? _elementHandlerDispatcher.ElementHandleDispatcher.fromJSHandle(scope, args[0]) : undefined
  326. });
  327. this._type_BindingCall = true;
  328. this._resolve = void 0;
  329. this._reject = void 0;
  330. this._promise = void 0;
  331. this._promise = new Promise((resolve, reject) => {
  332. this._resolve = resolve;
  333. this._reject = reject;
  334. });
  335. }
  336. promise() {
  337. return this._promise;
  338. }
  339. async resolve(params, metadata) {
  340. this._resolve((0, _jsHandleDispatcher.parseArgument)(params.result));
  341. this._dispose();
  342. }
  343. async reject(params, metadata) {
  344. this._reject((0, _errors.parseError)(params.error));
  345. this._dispose();
  346. }
  347. }
  348. exports.BindingCallDispatcher = BindingCallDispatcher;