Created
February 19, 2018 08:18
-
-
Save rippo/7e20d9300ed93727862ece38a0d3e4a7 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const puppeteer = require('puppeteer'); | |
/** | |
* This is a thin wrapper so that we use a singleton of | |
* the browser that puppeteer creates | |
*/ | |
class Browser { | |
setUp(done) { | |
const puppeteerOpts = this.options && this.options.puppeteer ? | |
this.options.puppeteer : | |
{}; | |
puppeteer.launch(puppeteerOpts).then(async b => { | |
this.setBrowser(b); | |
done(); | |
}); | |
} | |
setBrowser(b) { | |
this.browser = b; | |
const oldNewPage = this.browser.newPage.bind(this.browser); | |
this.browser.newPage = async function () { | |
const page = await oldNewPage(); | |
this.lastPage = page; | |
await page.setViewport({ width:1024, height:800}); | |
return page; | |
}; | |
} | |
setOptions(opts) { | |
this.options = opts; | |
} | |
test(promise) { | |
return (done) => { | |
//In CLI or attach this works, from code | |
// this.browser is undefined | |
console.log(this.browser); | |
promise(this.browser, this.options) | |
.then(() => done()).catch(done); | |
}; | |
} | |
} | |
/* | |
* Create a new browser and use a proxy to pass | |
* any puppeteer calls to the inner browser | |
*/ | |
module.exports = new Proxy(new Browser(), { | |
get: function(target, name) { | |
return name in target ? target[name].bind(target) : target.browser[name]; | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment