@lcrespilho/puppeteer-utils
v1.82.0
Published
Algumas funções que uso quase sempre no puppeteer.
Downloads
12
Readme
Classes
Functions
Typedefs
PuppeteerVideoRecorder
Kind: global class
new PuppeteerVideoRecorder()
Utiliza ffmpeg para gravar a sessão.
Example
const record = new PuppeteerVideoRecorder(page, 'myRecord');
await record.start();
await page.goto(...);
await record.stop();
// será criado o arquivo myRecord.mp4 no diretório atual.
puppeteerVideoRecorder.screencastFrameHandler()
Listener para o evento 'Page.screencastframe'.
Kind: instance method of PuppeteerVideoRecorder
Pardam: puppeteer.Protocol.Page.ScreencastFrameEvent _
PuppeteerVideoRecorder.PuppeteerVideoRecorder
Kind: static class of PuppeteerVideoRecorder
new PuppeteerVideoRecorder(page, [label])
Creates an instance of PuppeteerVideoRecorder.
| Param | Type | Default | Description | | --- | --- | --- | --- | | page | puppeteer.Page | | | | [label] | string | "'record'" | caminho relativo e nome do arquivo a ser gravado, sem especificar a extensão. Ex: "public/record" => arquivo record.mp4 em "./public". Default = 'record'. |
PuppeteerVideoRecorder.PuppeteerVideoRecorder : Array.<Frame>
Kind: static property of PuppeteerVideoRecorder
new PuppeteerVideoRecorder(page, [label])
Creates an instance of PuppeteerVideoRecorder.
| Param | Type | Default | Description | | --- | --- | --- | --- | | page | puppeteer.Page | | | | [label] | string | "'record'" | caminho relativo e nome do arquivo a ser gravado, sem especificar a extensão. Ex: "public/record" => arquivo record.mp4 em "./public". Default = 'record'. |
PuppeteerVideoRecorder.normalizeFrames(frames)
Normaliza o array de Frame's realizando as seguintes ações:
- transforma a propriedade
timestamp
, de float para natural, fazendo: - subtrai, de todos os timestamps, o timestamp do primeiro Frame. - divide todos os timestamps por 0.04s, que corresponde a 25fps: taxa escolhida para criar o vídeo de saída. - expande o array original, preenchendo os frames ausentes para formar um vídeo com 25fps.
- adiciona 2s de repetição do último frame, para dar tempo de vê-lo antes do player fechar.
Kind: static method of PuppeteerVideoRecorder
| Param | Type | | --- | --- | | frames | Array.<Frame> |
Example
Entrada: [{frameBuffer: f1, timestamp: 10.6}, {frameBuffer: f2, timestamp: 10.68}, {frameBuffer: f3, timestamp: 10.76}]
Saída: [{frameBuffer: f1, timestamp: 0}, {frameBuffer: f1, timestamp: 1}, {frameBuffer: f2, timestamp: 2}, {frameBuffer: f2, timestamp: 3}, {frameBuffer: f3, timestamp: 4}]
getFrameBlockTypes(page, site)
Verifica se o site do cliente bloqueia iframes same-origin ou other-origin, e se implementa Frame Busting.
Kind: global function
| Param | Type | Description | | --- | --- | --- | | page | puppeteer.Page | | | site | string | Site do cliente. |
waitForNetworkIdle(page, [timeout], [maxInflightRequests]) ⇒ Promise.<string>
Network-idle watcher. Wait until inflight requests <= maxInflightRequests
for at least timeout
ms.
Returns the last seen resource.
E.g.:
- waitForNetworkIdle(page, 500, 0), // equivalent to 'networkidle0'
- waitForNetworkIdle(page, 500, 2), // equivalent to 'networkidle2' https://github.com/GoogleChrome/puppeteer/issues/1353#issuecomment-356561654
Kind: global function
Returns: Promise.<string> - the last seen resource.
| Param | Type | Default | Description |
| --- | --- | --- | --- |
| page | puppeteer.Page | | |
| [timeout] | number | 500 | minimum time span with the condition inflight requests <= maxInflightRequests
holded, to consider the network idle. |
| [maxInflightRequests] | number | 0 | maximum inflight requests to consider the network idle. |
waitForEvent(page, event, [timeout])
The methods page.waitForNavigation
and frame.waitForNavigation
wait for the page
event domcontentloaded
at minimum. This function returns a promise that resolves as
soon as the specified page event
happens.
Kind: global function
| Param | Type | Description |
| --- | --- | --- |
| page | puppeteer.Page | |
| event | 'close' | 'console' | 'dialog' | 'domcontentloaded' | 'error' | 'frameattached' | 'framedetached' | 'framenavigated' | 'load' | 'metrics' | 'pageerror' | 'popup' | 'request' | 'requestfailed' | 'requestfinished' | 'response' | 'workercreated' | 'workerdestroyed' | Can be any event accepted by the method page.on()
. E.g.: "requestfinished" or "framenavigated". |
| [timeout] | number | optional time to wait. If not specified, waits forever. |
waitForRequestFinished(page, requestUrl, [timeout])
The methods page.waitForNavigation
and frame.waitForNavigation
wait for the page
event domcontentloaded
at minimum. This function returns a promise that resolves as
soon as the specified requestUrl
resource has finished downloading, or timeout
elapses.
Kind: global function
| Param | Type | Description | | --- | --- | --- | | page | puppeteer.Page | | | requestUrl | string | pass the exact url of the resource you want to wait for. Paths must be ended with slash "/". Don't forget that. | | [timeout] | number | optional time to wait. If not specified, waits forever. |
createFrame(page, [frameName])
Cria um iframe novo e o retorna.
Kind: global function
| Param | Type | Description | | --- | --- | --- | | page | puppeteer.Page | | | [frameName] | string | nome do frame criado |
waitForFrame(page, frameName, [timeout]) ⇒ Promise.<puppeteer.Frame> | Promise.<undefined>
Retorna uma promise que resolve com o primeiro frame que surgir em page
com nome frameName
.
Aguarda no máximo timeout
ms, ou infinito se timout
for omitido.
Kind: global function
| Param | Type | Description |
| --- | --- | --- |
| page | puppeteer.Page | página onde se deseja encontrar o frame. |
| frameName | string | nome do frame procurado em page
. |
| [timeout] | number | tempo máximo de espera. Se não especificado, aguarda infinitamente pela existência de frameName
em page
. |
getPerformanceMetrics(page)
Retorna um objeto contendo algumas métricas importantes de performance. Como essa função retorna métricas de carregamento, é importante garantir que essa função só será chamada após a página terminar de carregar, preferencialmente por completo. Esta função não garante isso; quem tem que garantir é o código chamador.
Kind: global function
| Param | Type | Description | | --- | --- | --- | | page | puppeteer.Page | página |
getRedirectChain(response) ⇒ Array.<string>
Retorna o chain de redirects de uma requisição fetch (qualquer recurso, não somente navegações).
Kind: global function
Returns: Array.<string> - Array de urls que participaram do chain de redirects. Se não teve redirects, retorna a url do response
passado como argumento.
| Param | Type | Description | | --- | --- | --- | | response | puppeteer.HTTPResponse | Response associado ao request que gerou o chain de redirects. |
pageRedirectRequest(page, redirects, requestAlreadyHandled) ⇒
Cria redirect(s) 307.
Kind: global function
Returns: Retorna uma função que desativa o(s) redirect(s).
| Param | Type | Default | Description | | --- | --- | --- | --- | | page | puppeteer.Page | | | | redirects | Array.<redirect> | | Array de regras de redirect | | requestAlreadyHandled | boolean | false | Se true, indica que esta função não deve executar request.continue(), caso já executado por outro listener. |
waitForSelector(page, selector)
Extensão ao método page.waitForSelector que aceita seletores AND (comma). Tem o funcionamento similar ao expect(page).toClick(selector, options) do pacote expect-puppeteer.
Kind: global function
| Param | Type | Description | | --- | --- | --- | | page | puppeteer.Page | | | selector | string | Seletor contendo ou não regras AND |
emulateMobile(page)
Emula um mobile "Nexus 5X".
Kind: global function
| Param | Type | | --- | --- | | page | puppeteer.Page |
emulateDesktop(page) ⇒ Promise.<any>
Emula um desktop 1800x900, userAgent Chrome 83.
Kind: global function
| Param | Type | | --- | --- | | page | puppeteer.Page |
closeOtherPages(page) ⇒ Promise.<any>
Fecha todas as abas do BrowserContext de page
passada como parâmetro, com exceção dela própria.
Kind: global function
| Param | Type | | --- | --- | | page | puppeteer.Page |
closeAllOtherPages(page) ⇒ Promise.<any>
Fecha todas as abas do browser (de todos os contextos), com exceção de page
passada como parâmetro.
Kind: global function
| Param | Type | | --- | --- | | page | puppeteer.Page |
beaconizeCollectHits(page)
Transform POST collect requests into GET requests, in order to facilitate in matching its contents.
Kind: global function
| Param | Type | | --- | --- | | page | puppeteer.Page |
defineDataLayerUtils(page)
Define dataModel and Observe dataLayer on the page.
Kind: global function
| Param | Type | | --- | --- | | page | puppeteer.Page |
toMatchDatalayerObject(mockFn, expectObjectSubset)
Matcher para push de dataLayer. Uso: expect(mockFn).toMatchDatalayerObject({event: 'sendTransaction'})
Kind: global function
| Param | Type | Description | | --- | --- | --- | | mockFn | jest.Mock.<any, any> | Mock do dataLayer.push | | expectObjectSubset | Object | Subconjunto do objeto que se deseja pesquisar no mock do dataLayer.push |
get([path])
Data Layer Model get method.
Kind: global function
| Param | Type | Description |
| --- | --- | --- |
| [path] | string | The path of the property on the model. If undefined
, returns the entire representation of the model. |
set(path, value)
Data Layer Model set method.
Kind: global function
| Param | Type | Description | | --- | --- | --- | | path | string | The of the property on the model. E.g.: 'a.b.c' | | value | * | The value to set on the property. E.g.: [1,2,3] |
validateCollectEvent(category, [action], [label], [value], [regexesOrStrings])
Helper para validação de eventos de collects
Kind: global function
| Param | Type | Description | | --- | --- | --- | | category | string | categoria do hit | | [action] | string | action do hit | | [label] | string | label do hit | | [value] | number | valor inteiro | | [regexesOrStrings] | Array.<(RegExp|string)> | Array de regex ou string para dar match no collect, não importa a ordem |
validateCollectEvent~predicate(req)
Kind: inner method of validateCollectEvent
| Param | Type | | --- | --- | | req | puppeteer.HTTPRequest |
redirect : Object
Regra de redirect.
Kind: global typedef
Properties
| Name | Type | Default | | --- | --- | --- | | requestMatch | RegExp | | | [resourceType] | 'document' | 'stylesheet' | 'image' | 'media' | 'font' | 'script' | 'texttrack' | 'xhr' | 'fetch' | 'ping' | 'eventsource' | 'websocket' | 'manifest' | 'other' | | | [redirectLocation] | string | "'about:blank'" |
dlPushListener : function
Generic callback for dataLayer push.
Kind: global typedef
| Param | Type | Description | | --- | --- | --- | | dlPayload | * | Payload de dataLayer |
Frame : Object
Objeto contendo 1 Buffer representando o frame/imagem, e seu timestamp correspondente.
Kind: global typedef
Properties
| Name | Type | Description | | --- | --- | --- | | timestamp | number | Timestamp do frame | | frameBuffer | Buffer | representação em buffer da string base64 que representa a imagem. |