How to use _onScriptParsed method in Puppeteer

Best JavaScript code snippet using puppeteer

Run Puppeteer automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

JSCoverage.js

Source: JSCoverage.js Github

copy
1const { helper, debugError, assert } = require('../helper')
2const { EVALUATION_SCRIPT_URL } = require('../executionContext')
3const { convertToDisjointRanges } = require('../__shared')
4
5class JSCoverage {
6  /**
7   * @param {Chrome|CRIConnection|CDPSession|Object} client
8   */
9  constructor (client) {
10    /**
11     * @type {Chrome|CRIConnection|CDPSession|Object}
12     * @private
13     */
14    this._client = client
15    /**
16     * @type {boolean}
17     * @private
18     */
19    this._enabled = false
20    this._scriptURLs = new Map()
21    this._scriptSources = new Map()
22    this._eventListeners = []
23    this._resetOnNavigation = false
24  }
25
26  /**
27   * @param {!{resetOnNavigation?: boolean, reportAnonymousScripts?: boolean}} options
28   */
29  async start (options = {}) {
30    assert(!this._enabled, 'JSCoverage is already enabled')
31    const { resetOnNavigation = true, reportAnonymousScripts = false } = options
32    this._resetOnNavigation = resetOnNavigation
33    this._reportAnonymousScripts = reportAnonymousScripts
34    this._enabled = true
35    this._scriptURLs.clear()
36    this._scriptSources.clear()
37    this._eventListeners = [
38      helper.addEventListener(
39        this._client,
40        'Debugger.scriptParsed',
41        this._onScriptParsed.bind(this)
42      ),
43      helper.addEventListener(
44        this._client,
45        'Runtime.executionContextsCleared',
46        this._onExecutionContextsCleared.bind(this)
47      )
48    ]
49    await Promise.all([
50      this._client.send('Profiler.enable'),
51      this._client.send('Profiler.startPreciseCoverage', {
52        callCount: false,
53        detailed: true
54      }),
55      this._client.send('Debugger.enable'),
56      this._client.send('Debugger.setSkipAllPauses', { skip: true })
57    ])
58  }
59
60  _onExecutionContextsCleared () {
61    if (!this._resetOnNavigation) return
62    this._scriptURLs.clear()
63    this._scriptSources.clear()
64  }
65
66  /**
67   * @param {!Object} event
68   */
69  async _onScriptParsed (event) {
70    // Ignore puppeteer-injected scripts
71    if (event.url === EVALUATION_SCRIPT_URL) return
72    // Ignore other anonymous scripts unless the reportAnonymousScripts option is true.
73    if (!event.url && !this._reportAnonymousScripts) return
74    try {
75      const response = await this._client.send('Debugger.getScriptSource', {
76        scriptId: event.scriptId
77      })
78      this._scriptURLs.set(event.scriptId, event.url)
79      this._scriptSources.set(event.scriptId, response.scriptSource)
80    } catch (e) {
81      // This might happen if the page has already navigated away.
82      debugError(e)
83      console.error(e)
84    }
85  }
86
87  /**
88   * @return {Promise<Array<CoverageEntry>>}
89   */
90  async stop () {
91    assert(this._enabled, 'JSCoverage is not enabled')
92    this._enabled = false
93    const [profileResponse] = await Promise.all([
94      this._client.send('Profiler.takePreciseCoverage'),
95      this._client.send('Profiler.stopPreciseCoverage'),
96      this._client.send('Profiler.disable'),
97      this._client.send('Debugger.disable')
98    ])
99    helper.removeEventListeners(this._eventListeners)
100
101    const coverage = []
102    for (const entry of profileResponse.result) {
103      let url = this._scriptURLs.get(entry.scriptId)
104      if (!url && this._reportAnonymousScripts) {
105        url = 'debugger://VM' + entry.scriptId
106      }
107      const text = this._scriptSources.get(entry.scriptId)
108      if (text === undefined || url === undefined) continue
109      const flattenRanges = []
110      for (const func of entry.functions) flattenRanges.push(...func.ranges)
111      const ranges = convertToDisjointRanges(flattenRanges)
112      coverage.push({ url, ranges, text })
113    }
114    return coverage
115  }
116}
117
118module.exports = JSCoverage
119
Full Screen

092a980e0f10c3d5a0f320539a5e2f6d9ebd2300_11_1.js

Source: 092a980e0f10c3d5a0f320539a5e2f6d9ebd2300_11_1.js Github

copy
1function ScriptAgent(require, exports, module) {
2    'use strict';
3
4    var Inspector = require("LiveDevelopment/Inspector/Inspector");
5    var DOMAgent = require("LiveDevelopment/Agents/DOMAgent");
6
7    var _load; // the load promise
8    var _urlToScript; // url -> script info
9    var _idToScript; // id -> script info
10    var _insertTrace; // the last recorded trace of a DOM insertion
11
12    /** Add a call stack trace to a node
13     * @param {integer} node id
14     * @param [{Debugger.CallFrame}] call stack
15     */
16    function _addTraceToNode(nodeId, trace) {
17        var node = DOMAgent.nodeWithId(nodeId);
18        node.trace = trace;
19    }
20
21    /** Get the script information for a given url
22     * @param {string} url
23     */
24    function scriptWithId(url) {
25        return _idToScript[url];
26    }
27
28    /** Get the script information for a given url
29     * @param {string} url
30     */
31    function scriptForURL(url) {
32        return _urlToScript[url];
33    }
34
35    // DOMAgent Event: Document root loaded
36    function _onGetDocument(res) {
37        Inspector.DOMDebugger.setDOMBreakpoint(res.root.nodeId, "subtree-modified");
38        _load.resolve();
39    }
40
41    // WebInspector Event: DOM.childNodeInserted
42    function _onChildNodeInserted(res) {
43        // res = {parentNodeId, previousNodeId, node}
44        if (_insertTrace) {
45            var node = DOMAgent.nodeWithId(res.node.nodeId);
46            node.trace = _insertTrace;
47            _insertTrace = undefined;
48        }
49    }
50
51    // WebInspector Event: Debugger.scriptParsed
52    function _onScriptParsed(res) {
53        // res = {scriptId, url, startLine, startColumn, endLine, endColumn, isContentScript, sourceMapURL}
54        _idToScript[res.scriptId] = res;
55        _urlToScript[res.url] = res;
56    }
57
58    // WebInspector Event: Debugger.scriptFailedToParse
59    function _onScriptFailedToParse(res) {
60        // res = {url, scriptSource, startLine, errorLine, errorMessage}
61    }
62
63    // WebInspector Event: Debugger.paused
64    function _onPaused(res) {
65        // res = {callFrames, reason, data}
66        switch (res.reason) {
67
68        // Exception
69        case "exception":
70            Inspector.Debugger.resume();
71            // var callFrame = res.callFrames[0];
72            // var script = scriptWithId(callFrame.location.scriptId);
73            break;
74
75        // DOMBreakpoint
76        case "DOM":
77            Inspector.Debugger.resume();
78            if (res.data.type === "subtree-modified" && res.data.insertion === true) {
79                _insertTrace = res.callFrames;
80            }
81            break;
82        }
83
84    }
85
86    /** Initialize the agent */
87    function load() {
88        _urlToScript = {};
89        _idToScript = {};
90        _load = new $.Deferred();
91        Inspector.Debugger.enable();
92        Inspector.Debugger.setPauseOnExceptions("uncaught");
93        Inspector.on("DOMAgent.getDocument", _onGetDocument);
94        Inspector.on("Debugger.scriptParsed", _onScriptParsed);
95        Inspector.on("Debugger.scriptFailedToParse", _onScriptFailedToParse);
96        Inspector.on("Debugger.paused", _onPaused);
97        Inspector.on("DOM.childNodeInserted", _onChildNodeInserted);
98        return _load;
99    }
100
101    /** Clean up */
102    function unload() {
103        Inspector.off("DOMAgent.getDocument", _onGetDocument);
104        Inspector.off("Debugger.scriptParsed", _onScriptParsed);
105        Inspector.off("Debugger.scriptFailedToParse", _onScriptFailedToParse);
106        Inspector.off("Debugger.paused", _onPaused);
107        Inspector.off("DOM.childNodeInserted", _onChildNodeInserted);
108    }
109
110    // Export public functions
111    exports.scriptWithId = scriptWithId;
112    exports.scriptForURL = scriptForURL;
113    exports.load = load;
114    exports.unload = unload;
115}
Full Screen

68030e5486ab323f874773f202f4acd09a20f287_11_1.js

Source: 68030e5486ab323f874773f202f4acd09a20f287_11_1.js Github

copy
1function ScriptAgent(require, exports, module) {
2    'use strict';
3
4    var Inspector = require("LiveDevelopment/Inspector/Inspector");
5    var DOMAgent = require("LiveDevelopment/Agents/DOMAgent");
6
7    var _load; // the load promise
8    var _urlToScript; // url -> script info
9    var _idToScript; // id -> script info
10    var _insertTrace; // the last recorded trace of a DOM insertion
11
12    /** Add a call stack trace to a node
13     * @param {integer} node id
14     * @param [{Debugger.CallFrame}] call stack
15     */
16    function _addTraceToNode(nodeId, trace) {
17        var node = DOMAgent.nodeWithId(nodeId);
18        node.trace = trace;
19    }
20
21    /** Get the script information for a given url
22     * @param {string} url
23     */
24    function scriptWithId(url) {
25        return _idToScript[url];
26    }
27
28    /** Get the script information for a given url
29     * @param {string} url
30     */
31    function scriptForURL(url) {
32        return _urlToScript[url];
33    }
34
35    // DOMAgent Event: Document root loaded
36    function _onGetDocument(res) {
37        Inspector.DOMDebugger.setDOMBreakpoint(res.root.nodeId, "subtree-modified");
38        _load.resolve();
39    }
40
41    // WebInspector Event: DOM.childNodeInserted
42    function _onChildNodeInserted(res) {
43        // res = {parentNodeId, previousNodeId, node}
44        if (_insertTrace) {
45            var node = DOMAgent.nodeWithId(res.node.nodeId);
46            node.trace = _insertTrace;
47            _insertTrace = undefined;
48        }
49    }
50
51    // WebInspector Event: Debugger.scriptParsed
52    function _onScriptParsed(res) {
53        // res = {scriptId, url, startLine, startColumn, endLine, endColumn, isContentScript, sourceMapURL}
54        _idToScript[res.scriptId] = res;
55        _urlToScript[res.url] = res;
56    }
57
58    // WebInspector Event: Debugger.scriptFailedToParse
59    function _onScriptFailedToParse(res) {
60        // res = {url, scriptSource, startLine, errorLine, errorMessage}
61    }
62
63    // WebInspector Event: Debugger.paused
64    function _onPaused(res) {
65        // res = {callFrames, reason, data}
66        switch (res.reason) {
67
68        // Exception
69        case "exception":
70            Inspector.Debugger.resume();
71            // var callFrame = res.callFrames[0];
72            // var script = scriptWithId(callFrame.location.scriptId);
73            break;
74
75        // DOMBreakpoint
76        case "DOM":
77            Inspector.Debugger.resume();
78            if (res.data.type === "subtree-modified" && res.data.insertion === true) {
79                _insertTrace = res.callFrames;
80            }
81            break;
82        }
83
84    }
85
86    /** Initialize the agent */
87    function load() {
88        _urlToScript = {};
89        _idToScript = {};
90        _load = new $.Deferred();
91        Inspector.Debugger.enable();
92        Inspector.Debugger.setPauseOnExceptions("uncaught");
93        Inspector.on("DOMAgent.getDocument", _onGetDocument);
94        Inspector.on("Debugger.scriptParsed", _onScriptParsed);
95        Inspector.on("Debugger.scriptFailedToParse", _onScriptFailedToParse);
96        Inspector.on("Debugger.paused", _onPaused);
97        Inspector.on("DOM.childNodeInserted", _onChildNodeInserted);
98        return _load;
99    }
100
101    /** Clean up */
102    function unload() {
103        Inspector.off("DOMAgent.getDocument", _onGetDocument);
104        Inspector.off("Debugger.scriptParsed", _onScriptParsed);
105        Inspector.off("Debugger.scriptFailedToParse", _onScriptFailedToParse);
106        Inspector.off("Debugger.paused", _onPaused);
107        Inspector.off("DOM.childNodeInserted", _onChildNodeInserted);
108    }
109
110    // Export public functions
111    exports.scriptWithId = scriptWithId;
112    exports.scriptForURL = scriptForURL;
113    exports.load = load;
114    exports.unload = unload;
115}
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest

Run JavaScript Tests on LambdaTest Cloud Grid

Execute automation tests with Puppeteer on a cloud-based Grid of 3000+ real browsers and operating systems for both web and mobile applications.

Test now for Free
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)