4

I am trying to use a local file in Headless Chromium started through Puppeteer.

I always run into the following error:

'Cross origin requests are only supported for protocol schemes: http, data, chrome, https'

I did attempt to set --allow-file-access-from-files.

It can be reproduced as follows:

const puppeteer = require('puppeteer');

puppeteer.launch({headless:true,args:['--allow-file-access-from-files']}).then(
  async browser => {
    const page = await browser.newPage();
    await page.setContent('<html><head><meta charset="UTF-8"></head><body><div>A page</div></body></html>');
    await page.addScriptTag({url:"https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"});
    await page.on('console', msg => console.log('PAGE LOG:', msg.text()));
    await page.evaluate (() => {
      $.get('file:///..../cors.js')
        .done(
           _ => console.log('done')
        ).fail(
          e => console.log('fail:'+JSON.stringify(e))
        );
    });
  await browser.close();
  }
);

Looking at the running processes, it does look like Chromium was started with the option.

All tips warmly welcomed!

juanmirocks
  • 4,786
  • 5
  • 46
  • 46
Peter Coppens
  • 103
  • 2
  • 7

1 Answers1

1

You are attempting to load your local file from the Page DOM Environment using $.get(), which will not work because it is a violation of the same-origin policy.

The Chromium flag --allow-file-access-from-files is described below:

By default, file:// URIs cannot read other file:// URIs. This is an override for developers who need the old behavior for testing.

This flag does not apply to your scenario.

You can use the Node.js function fs.readFileSync() instead to obtain the content of your file and pass it to page.evaluate():

const fs = require('fs');

const file_path = '/..../cors.js';
const file_content = fs.existsSync(file_path) ? fs.readFileSync(file_path, 'utf8') : '';

await page.evaluate(file_content => {
  console.log(file_content);
}, file_content);
Grant Miller
  • 27,532
  • 16
  • 147
  • 165
  • 1
    Unfortunately I cannot change the actual code as you suggest. But you did point me in the right direction. Disabling cors check when launching chromium makes it work for me. Tx! – Peter Coppens Jul 23 '18 at 18:21