|
3 | 3 | module.exports = (page, opts) => { |
4 | 4 | const cdp = page._client() |
5 | 5 | let onFrame |
| 6 | + let hasFrameListener = false |
6 | 7 |
|
7 | | - cdp.on('Page.screencastFrame', ({ data, metadata, sessionId }) => { |
| 8 | + const onScreencastFrame = ({ data, metadata, sessionId }) => { |
8 | 9 | cdp.send('Page.screencastFrameAck', { sessionId }).catch(() => {}) |
9 | | - if (metadata.timestamp) onFrame(data, metadata) |
10 | | - }) |
| 10 | + if (metadata.timestamp && onFrame) onFrame(data, metadata) |
| 11 | + } |
| 12 | + |
| 13 | + const attachFrameListener = () => { |
| 14 | + if (hasFrameListener) return |
| 15 | + cdp.on('Page.screencastFrame', onScreencastFrame) |
| 16 | + hasFrameListener = true |
| 17 | + } |
| 18 | + |
| 19 | + const detachFrameListener = () => { |
| 20 | + if (!hasFrameListener) return |
| 21 | + cdp.off('Page.screencastFrame', onScreencastFrame) |
| 22 | + hasFrameListener = false |
| 23 | + } |
11 | 24 |
|
12 | 25 | return { |
13 | 26 | // https://chromedevtools.github.io/devtools-protocol/tot/Page/#method-startScreencast |
14 | | - start: () => cdp.send('Page.startScreencast', opts), |
| 27 | + start: () => { |
| 28 | + attachFrameListener() |
| 29 | + return cdp.send('Page.startScreencast', opts) |
| 30 | + }, |
15 | 31 | onFrame: fn => (onFrame = fn), |
16 | | - stop: () => cdp.send('Page.stopScreencast').catch(() => {}) |
| 32 | + stop: () => { |
| 33 | + detachFrameListener() |
| 34 | + return cdp.send('Page.stopScreencast').catch(() => {}) |
| 35 | + } |
17 | 36 | } |
18 | 37 | } |
0 commit comments