Load external or inline scripts in Playwright

Playwright offers a couple of ways to add scripts to the page(s) you are working with.

  • Load external script in the head
  • Add an inline script
  • Load a script from node_modules or other path

Examples of the different ways to add and use a script in Playwright:

External script

    await page.addScriptTag({ url: 'https://cdn.jsdelivr.net/gh/cferdinandi/smooth-scroll/dist/smooth-scroll.polyfills.min.js' });

Inline script

    function functionToInject (){
        return 1+1;
    }
    
    function otherFunctionToInject(input){
        return 6
    }

    await page.addScriptTag({ content: `${functionToInject} ${otherFunctionToInject}`});
    var data = await page.evaluate(function(){
        console.log('Running inside a browser')
        return functionToInject() + otherFunctionToInject();
    });
    
    console.log(data);

Path

with fake data

console.log(`Current directory: ${process.cwd()}`);
// Get current working directory

await page.addScriptTag({path: 'public\\js\\build\\report_bundle.js'});

Passing values with page.evaluate

Not tested. Found it in Youtube video.

await page.goto('https://google.com')

const pizza = 'Hey Pizza'

await page.evaluate((pizza) => {
    console.log('Pizza here:', pizza)
}, pizza);

Source:

https://stackoverflow.com/questions/48207414/how-can-i-dynamically-inject-functions-to-evaluate-using-puppeteer

Next:

Previous:

Edit this page on Github