diff --git a/examples/features.js b/examples/features.js index 7e4d277a..6c28f811 100644 --- a/examples/features.js +++ b/examples/features.js @@ -19,7 +19,7 @@ var Browser = require('../lib/Browser'); var browser = new Browser(); browser.newPage().then(async page => { - var modernizrPath = path.join('..', 'third_party', 'phantomjs', 'examples', 'modernizr.js'); + var modernizrPath = path.join(__dirname, '../third_party/phantomjs/examples/modernizr.js'); await page.injectFile(modernizrPath); page.on('consolemessage', console.log); await page.evaluate(detectFeatures); diff --git a/lib/Page.js b/lib/Page.js index 51b12074..ae4877e8 100644 --- a/lib/Page.js +++ b/lib/Page.js @@ -128,11 +128,13 @@ class Page extends EventEmitter { * @return {!Promise} */ async injectFile(filePath) { - let callback; - let promise = new Promise(fulfill => callback = fulfill); - let expression = fs.readFile(filePath, 'utf8', (err, data) => callback({err, data})); - await promise; - return this._client.send('Runtime.evaluate', { expression, returnByValue: true }); + const contents = await new Promise((resolve, reject) => { + fs.readFile(filePath, 'utf8', (err, data) => { + if (err) return reject(err); + resolve(data); + }); + }); + return this._client.send('Runtime.evaluate', { expression: contents, returnByValue: true }); } /** diff --git a/test/assets/injectedfile.js b/test/assets/injectedfile.js new file mode 100644 index 00000000..57b4464f --- /dev/null +++ b/test/assets/injectedfile.js @@ -0,0 +1 @@ +__injected = 42; diff --git a/test/test.js b/test/test.js index ed5f25d9..24485431 100644 --- a/test/test.js +++ b/test/test.js @@ -104,6 +104,15 @@ describe('Puppeteer', function() { })); }); + describe('Page.injectFile', function() { + it('should fail when navigating to bad url', SX(async function() { + const helloPath = path.join(__dirname, './assets/injectedfile.js'); + await page.injectFile(helloPath); + const result = await page.evaluate(() => __injected); + expect(result).toBe(42); + })); + }); + describe('Frame.evaluate', function() { let FrameUtils = require('./frame-utils'); it('should have different execution contexts', SX(async function() {