UNPKG

2.96 kBJavaScriptView Raw
1const {Page} = require('./Page');
2const {helper} = require('./helper');
3
4class Target {
5 /**
6 * @param {!Protocol.Target.TargetInfo} targetInfo
7 * @param {!Puppeteer.BrowserContext} browserContext
8 * @param {!function():!Promise<!Puppeteer.CDPSession>} sessionFactory
9 * @param {boolean} ignoreHTTPSErrors
10 * @param {?Puppeteer.Viewport} defaultViewport
11 * @param {!Puppeteer.TaskQueue} screenshotTaskQueue
12 */
13 constructor(targetInfo, browserContext, sessionFactory, ignoreHTTPSErrors, defaultViewport, screenshotTaskQueue) {
14 this._targetInfo = targetInfo;
15 this._browserContext = browserContext;
16 this._targetId = targetInfo.targetId;
17 this._sessionFactory = sessionFactory;
18 this._ignoreHTTPSErrors = ignoreHTTPSErrors;
19 this._defaultViewport = defaultViewport;
20 this._screenshotTaskQueue = screenshotTaskQueue;
21 /** @type {?Promise<!Puppeteer.Page>} */
22 this._pagePromise = null;
23 this._initializedPromise = new Promise(fulfill => this._initializedCallback = fulfill);
24 this._isClosedPromise = new Promise(fulfill => this._closedCallback = fulfill);
25 this._isInitialized = this._targetInfo.type !== 'page' || this._targetInfo.url !== '';
26 if (this._isInitialized)
27 this._initializedCallback(true);
28 }
29
30 /**
31 * @return {!Promise<!Puppeteer.CDPSession>}
32 */
33 createCDPSession() {
34 return this._sessionFactory();
35 }
36
37 /**
38 * @return {!Promise<?Page>}
39 */
40 async page() {
41 if ((this._targetInfo.type === 'page' || this._targetInfo.type === 'background_page') && !this._pagePromise) {
42 this._pagePromise = this._sessionFactory()
43 .then(client => Page.create(client, this, this._ignoreHTTPSErrors, this._defaultViewport, this._screenshotTaskQueue));
44 }
45 return this._pagePromise;
46 }
47
48 /**
49 * @return {string}
50 */
51 url() {
52 return this._targetInfo.url;
53 }
54
55 /**
56 * @return {"page"|"background_page"|"service_worker"|"other"|"browser"}
57 */
58 type() {
59 const type = this._targetInfo.type;
60 if (type === 'page' || type === 'background_page' || type === 'service_worker' || type === 'browser')
61 return type;
62 return 'other';
63 }
64
65 /**
66 * @return {!Puppeteer.Browser}
67 */
68 browser() {
69 return this._browserContext.browser();
70 }
71
72 /**
73 * @return {!Puppeteer.BrowserContext}
74 */
75 browserContext() {
76 return this._browserContext;
77 }
78
79 /**
80 * @return {Puppeteer.Target}
81 */
82 opener() {
83 const { openerId } = this._targetInfo;
84 if (!openerId)
85 return null;
86 return this.browser()._targets.get(openerId);
87 }
88
89 /**
90 * @param {!Protocol.Target.TargetInfo} targetInfo
91 */
92 _targetInfoChanged(targetInfo) {
93 this._targetInfo = targetInfo;
94
95 if (!this._isInitialized && (this._targetInfo.type !== 'page' || this._targetInfo.url !== '')) {
96 this._isInitialized = true;
97 this._initializedCallback(true);
98 return;
99 }
100 }
101}
102
103helper.tracePublicAPI(Target);
104
105module.exports = {Target};