Created
May 31, 2017 16:37
-
-
Save robhammond/83142a1646c44c20aff2a04e672aa5a2 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 util = require('util'); | |
var url = 'http://localhost:3000/test'; // should be set over cli | |
const chrome = require('chrome-remote-interface'); | |
function onPageLoad(Runtime) { | |
const href = "document.querySelectorAll('a')"; | |
return Runtime.evaluate({ | |
expression: href | |
}).then(result => { | |
var links = result.result; | |
console.log(util.inspect(links, false, null)); | |
for (let item of links) { | |
console.log(item.href); | |
} | |
}); | |
} | |
const { | |
ChromeLauncher | |
} = require('lighthouse/lighthouse-cli/chrome-launcher'); | |
/** | |
* Launches a debugging instance of Chrome on port 9222. | |
* @param {boolean=} headless True (default) to launch Chrome in headless mode. | |
* Set to false to launch Chrome normally. | |
* @return {Promise<ChromeLauncher>} | |
*/ | |
function launchChrome(headless = true) { | |
const launcher = new ChromeLauncher({ | |
port: 9222, | |
autoSelectChrome: true, // False to manually select which Chrome install. | |
additionalFlags: [ | |
'--window-size=412,732', | |
'--disable-gpu', | |
headless ? '--headless' : '' | |
] | |
}); | |
return launcher.run().then(() => launcher) | |
.catch(err => { | |
return launcher.kill().then(() => { // Kill Chrome if there's an error. | |
throw err; | |
}, console.error); | |
}); | |
} | |
launchChrome().then(launcher => { | |
chrome(protocol => { | |
// Extract the parts of the DevTools protocol we need for the task. | |
// See API docs: https://chromedevtools.github.io/devtools-protocol/ | |
const { | |
Page, | |
Runtime | |
} = protocol; | |
// First, need to enable the domains we're going to use. | |
Promise.all([ | |
Page.enable(), | |
Runtime.enable() | |
]).then(() => { | |
Page.navigate({ | |
url: url | |
}); | |
// Wait for window.onload before doing stuff. | |
Page.loadEventFired(() => { | |
onPageLoad(Runtime).then(() => { | |
protocol.close(); | |
launcher.kill(); // Kill Chrome. | |
}); | |
}); | |
}); | |
}).on('error', err => { | |
throw Error('Cannot connect to Chrome:' + err); | |
}); | |
}); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment