Created
October 3, 2018 11:48
-
-
Save benzaremean/cc57a7690e928f0c2676fc0b146a5230 to your computer and use it in GitHub Desktop.
service to intercept chrome
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 path = require('path'); | |
const CDP = require('chrome-remote-interface'); | |
class EavesDropService { | |
constructor() { | |
this.seleniumHost = undefined; | |
this.urlsRegexToTrack = /search|reserve|initial|baskets|create_payment_resource|paypal|orderhistory/; | |
this.urlsRegexToIgnore = /analytics|facebook|smetrics/; | |
} | |
shouldAttemptRemoteDebugConnection() { | |
return browser.desiredCapabilities.browserName === 'chrome'; | |
} | |
async beforeSession(config) { | |
this.seleniumHost = config.host; | |
} | |
async initChromeDevtoolsProtocolAndEnableNetworkDebugging() { | |
try { | |
await browser.url('chrome://version'); | |
const cmdLineElemText = await browser.getText('#command_line'); | |
let port = parseInt( | |
cmdLineElemText.match(/--remote-debugging-port=(\d*)/)[1], | |
10 | |
); | |
/** | |
* newer Chrome versions store port in DevToolsActivePort file | |
*/ | |
if (port === 0) { | |
const userDataDir = cmdLineElemText | |
.match(/--user-data-dir=([^-]*)/)[1] | |
.trim(); | |
await browser.url( | |
`file:///${path.join(userDataDir, 'DevToolsActivePort')}` | |
); | |
const response = await browser.getText('<pre>'); | |
port = parseInt(response.split('\n').shift(), 10); | |
} | |
this.client = await CDP({ | |
port, | |
host: this.seleniumHost, | |
}); | |
await this.client.Network.enable(); | |
console.log( | |
`Successfully enabled Chrome Network debugging on port ${port}` | |
); | |
} catch (e) { | |
console.warn( | |
`Could not initialise Chrome Developer Tools Protocol\n${e}` | |
); | |
} | |
} | |
async before() { | |
if (this.shouldAttemptRemoteDebugConnection()) { | |
await this.initChromeDevtoolsProtocolAndEnableNetworkDebugging(); | |
!!this.client && | |
this.client.on('Network.responseReceived', params => { | |
const { url, status } = params.response; | |
const shouldTrack = | |
this.urlsRegexToTrack.test(url) && | |
!this.urlsRegexToIgnore.test(url); | |
const statusAsString = status.toString(); | |
const returned4or5Code = | |
statusAsString.startsWith('4') || statusAsString.startsWith('5'); | |
if (shouldTrack && returned4or5Code) { | |
// DO WHAT YOU WANT HERE | |
} | |
}); | |
} | |
} | |
async after() { | |
!!this.client && (await this.client.close()); | |
} | |
} | |
module.exports = new EavesDropService(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment