Skip to content

Instantly share code, notes, and snippets.

@andrewhampton
Created August 31, 2016 13:25
Show Gist options
  • Save andrewhampton/95f1232716e08ad8ba22090c567b7dae to your computer and use it in GitHub Desktop.
Save andrewhampton/95f1232716e08ad8ba22090c567b7dae to your computer and use it in GitHub Desktop.
Stupid Simple Poll Renderer
const {app, BrowserWindow, ipcMain} = require('electron')
const http = require('http')
const url = require('url')
app.disableHardwareAcceleration()
let window
app.once('ready', () => {
window = new BrowserWindow({
show: false,
frame: false,
webPreferences: {
nodeIntegration: false,
offscreen: true,
preload: `${__dirname}/readyCheck.js`,
webSecurity: false
}
})
http.createServer((req, res) => {
let params = url.parse(req.url, true).query
if (params.screenshot_url) {
res.statusCode = 200
res.setHeader('Content-type', 'image/png; charset=binary')
res.setHeader('Transfer-Encoding', 'chunked')
readyPage(params.screenshot_url, parseInt(params.width), parseInt(params.height), res)
} else {
res.statusCode = 404
res.end()
}
}).listen(3000, '127.0.0.1', () => {
console.log('server listening')
})
})
const readyPage = (url, width, height, res) => {
console.log(`loading ${width}x${height} ${url}`)
window.setBounds({x: 0, y: 0, width: width, height: height})
window.loadURL(url, {userAgent: 'PollEverywhere/Poll Renderer'})
window.webContents.once('did-finish-load', () => {
if (url.includes("https://viz.polleverywhere.com")) {
window.webContents.executeJavaScript('__electron__checkVizReady()')
} else {
takeScreenshot(res)
}
})
ipcMain.once('viz-loaded', (event, arg) => {
takeScreenshot(res)
})
}
const takeScreenshot = (res) => {
window.capturePage((data) => {
res.end(data.toPng(), 'binary')
})
}
{
"name": "electron-offscreen",
"version": "0.0.1",
"main": "index.js",
"dependencies": {
"electron": "^1.3.4"
},
"devDependencies": {},
"scripts": {
"start": "electron index.js",
"start-linux": "xvfb-run --server-args=\"-screen 0 1600x900x24\" node_modules/electron/dist/electron index.js"
}
}
const {ipcRenderer} = require('electron')
process.once('loaded', () => {
global.__electron__ipc = ipcRenderer
global.__electron__checkVizReady = () => {
console.log('[Worker is loaded?: ' + PollEv.app.loaded())
if (PollEv.app.loaded()) {
window.requestAnimationFrame(function () {
console.log('[Worker ##{process.pid}] sending event viz-loaded')
global.__electron__ipc.send('viz-loaded')
})
} else {
setTimeout(global.__electron__checkVizReady, 500)
}
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment