Inject a script using puppeteer to make the functions usable from the webpage

  javascript, puppeteer

I’m using puppeteer to load a webpage that has a canvas that I want to record, with CCapture.js

I’ve tried all sorts of things, but no matter what I cannot get the recorder to successfully start in a page.evaluate, get various errors with CCapture being undefined.

I’ve tried using require at the top
I’ve tried using addScriptTag
I’ve tried using readFileSync to include it
I’ve also tried returning the capture object from the page.evaluate and calling i

const puppeteer = require('puppeteer');
const fs = require('fs');
const config = require('./login.json');
// const cc = require('./build/CCapture.all.min.js')

// const cc = require('./build/CCapture.all.min.js')

(async () => {
    function delay(time) {
      return new Promise(function(resolve) {
        setTimeout(resolve, time)
      });
    }
    try {

        const cookiesString = fs.readFileSync('./cookies.json', 'utf8');
        const cookies = JSON.parse(cookiesString);
        const browser = await puppeteer.launch({
            args: ["--no-sandbox"]
        });
        const page = await browser.newPage();
        await page.setViewport({width: 1920, height: 1080});
        await page.setCookie.apply(page, cookies);
        await page.goto(config.testurl);
        console.log(page.url());
        //wait for canvas to load
        await delay(1000);

        // try this later?
        // await page.exposeFunction('CCapture', canvas =>
        //     cc.capture('canvas'))

        // await page.addScriptTag({path: './build/CCapture.all.min.js'})
        await page.addScriptTag({path: './src/webm-writer-0.2.0.js'})
        await page.addScriptTag({path: './src/download.js'})
        await page.addScriptTag({ path: './src/tar.js' })
        // await page.addScriptTag({ path: './src/CCapture.js' })

        const cc = fs.readFileSync('./build/CCapture.all.min.js', 'utf8')
        await page.evaluateOnNewDocument(cc)

        var canvas = await page.evaluate(() => {
            let canvas = document.getElementById('mainCanvas');
            return canvas;
        });
        console.log(canvas);

        var capturer = await page.evaluate(() => {
            var capturer = new CCapture({
                format: 'png',
                framerate: 2,
                name: 'test',
                verbose: true,
                timeLimit: 10,
                autoSaveTime: 2

            })
            return capturer

        })
        await page.close();
        await browser.close();
    } catch(e){
        console.log(e)
    }
})();

Source: Ask Javascript Questions

LEAVE A COMMENT