API Documentation
July 8, 2018 · View on GitHub
Chromeless provides TypeScript typings.
Chromeless constructor options
new Chromeless(options: ChromelessOptions)
debug: booleanShow debug output — Default:falseremote: booleanUse remote chrome process — Default:falseimplicitWait: booleanWait for element to exist before executing commands — Default:falsewaitTimeout: numberTime in ms to wait for element to appear — Default:10000scrollBeforeClick: booleanScroll to element before clicking, usefull if element is outside of viewport — Default:falseviewport: anyViewport dimensions — Default:{width: 1440, height: 900, scale: 1}launchChrome: booleanAuto-launch chrome (local) — Default:truecdp: CDPOptionsChome Debugging Protocol Options — Default:{host: 'localhost', port: 9222, secure: false, closeTab: true}
Chromeless methods
Chrome methods
goto(url: string, timeout?: number)setUserAgent(useragent: string)click(selector: string, x?: number, y?: number)wait(timeout: number)wait(selector: string, timeout?: number)- [
wait(fn: (...args: any[]) => boolean, ...args: any[])] - Not implemented yet clearCache()clearStorage(origin: string, storageTypes: string)focus(selector: string)press(keyCode: number, count?: number, modifiers?: any)type(input: string, selector?: string)back()- Not implemented yetforward()- Not implemented yetrefresh()- Not implemented yetmousedown(selector: string)mouseup(selector: string)scrollTo(x: number, y: number)scrollToElement(selector: string)setHtml(html: string)setViewport(options: DeviceMetrics)evaluate<U extends any>(fn: (...args: any[]) => void, ...args: any[])inputValue(selector: string)exists(selector: string)screenshot(selector: string, options: ScreenshotOptions)pdf(options?: PdfOptions)html()cookies()cookies(name: string)cookies(query: CookieQuery)- Not implemented yetallCookies()setCookies(name: string, value: string)setCookies(cookie: Cookie)setCookies(cookies: Cookie[])deleteCookies(name: string)clearCookies()
end(): Promise
End the Chromeless session. Locally this will disconnect from Chrome. Over the Proxy, this will end the session, terminating the Lambda function. It returns the last value that has been evaluated.
await chromeless.end()
goto(url: string, timeout?: number): Chromeless
Navigate to a URL.
Arguments
url- URL to navigate totimeout-How long to wait for page to load (default is value of waitTimeout option)
Example
await chromeless.goto('https://google.com/')
setUserAgent(useragent: string): Chromeless
Set the useragent of the browser. It should be called before .goto().
Arguments
useragent- UserAgent to use
Example
await chromeless.setUserAgent('Custom Chromeless UserAgent x.x.x')
click(selector: string, x?: number, y?: number): Chromeless
Click on something in the DOM.
Arguments
selector- DOM selector for element to clickx- Offset from the left of the element, default width/2y- Offset from the top of the element, default height/2
Example
await chromeless.click('#button')
await chromeless.click('#button', 20, 100)
wait(timeout: number): Chromeless
Wait for some duration. Useful for waiting for things download.
Arguments
timeout- How long to wait, in ms
Example
await chromeless.wait(1000)
wait(selector: string, timeout?: number): Chromeless
Wait until something appears. Useful for waiting for things to render.
Arguments
selector- DOM selector to wait fortimeout- How long to wait for element to appear (default is value of waitTimeout option)
Example
await chromeless.wait('div#loaded')
await chromeless.wait('div#loaded', 1000)
wait(fn: (...args: any[]) => boolean, ...args: any[]): Chromeless
Not implemented yet
Wait until a function returns. You can also return some Promise that will be resolved at some point.
Arguments
fn- Function to wait for[arguments]- Arguments to pass to the function
Example
await chromeless.wait(() => {
return new Promise((resolve, reject) => {
// do something async, setTimeout...
resolve();
});
})
clearCache(): Chromeless
Clears browser cache.
Service workers and Storage (IndexedDB, WebSQL, etc) needs to be cleared separately. More information at the Chrome Devtools Protocol website.
Example
await chromeless.clearCache()
clearStorage(origin: string, storageTypes: string): Chromeless
Clears browser storage.
Arguments
-
origin- Security origin for the storage type we wish to clear -
storageTypes- A string comma separated list of chrome storage types. Allowed values include: appcache, cookies, file_systems, indexeddb, local_storage, shader_cache, websql, service_workers, cache_storage, all, other. More information at the Chrome Devtools Protocol website.
Example
await chromeless.clearStorage('http://localhost', 'local_storage, websql')
await chromeless.clearStorage('*', 'all')
focus(selector: string): Chromeless
Provide focus on a DOM element.
Arguments
selector- DOM selector to focus
Example
await chromeless.focus('input#searchField')
press(keyCode: number, count?: number, modifiers?: any): Chromeless
Send a key press. Enter, for example.
Arguments
keyCode- Key code to sendcount- How many times to send the key pressmodifiers- Modifiers to send along with the press (e.g. control, command, or alt)
Example
await chromeless.press(13)
type(input: string, selector?: string): Chromeless
Type something (into a field, for example).
Arguments
input- String to typeselector- DOM element to type into
Example
const result = await chromeless
.goto('https://www.google.com')
.type('chromeless', 'input[name="q"]')
back() - Not implemented yet
Not implemented yet
forward() - Not implemented yet
Not implemented yet
refresh() - Not implemented yet
Not implemented yet
mousedown(selector: string): Chromeless
Send mousedown event on something in the DOM.
Arguments
selector- DOM selector for element to send mousedown event
Example
await chromeless.mousedown('#item')
mouseup(selector: string): Chromeless
Send mouseup event on something in the DOM.
Arguments
selector- DOM selector for element to send mouseup event
Example
await chromeless.mouseup('#placeholder')
scrollTo(x: number, y: number): Chromeless
Scroll to somewhere in the document.
Arguments
x- Offset from the left of the documenty- Offset from the top of the document
Example
await chromeless.scrollTo(0, 500)
scrollToElement(selector: string): Chromeless
Scroll to location of element. Behavior is simiar to <a href="#fragment"></a> — target element will be at the top of viewport
Arguments
selector- DOM selector for element to scroll to
Example
await chromeless.scrollToElement('.button')
setHtml(html: string): Chromeless
Sets given markup as the document's HTML.
Arguments
html- HTML to set as the document's markup.
Example
await chromeless.setHtml('<h1>Hello world!</h1>')
setExtraHTTPHeaders(headers: Headers): Chromeless
Sets extra HTTP headers.
Arguments
headers- headers as keys / values of JSON object
Example
await chromeless.setExtraHTTPHeaders({
'accept-language': 'en-US,en;q=0.8'
})
setViewport(options:DeviceMetrics)
Resize the viewport. Useful if you want to capture more or less of the document in a screenshot.
Arguments
options- DeviceMetrics object
Example
await chromeless.setViewport({width: 1024, height: 600, scale: 1})
evaluate(fn: (...args: any[]) => void, ...args: any[]): Chromeless
Evaluate Javascript code within Chrome in the context of the DOM. Returns the resulting value or a Promise.
Arguments
fn- Function to evaluate within Chrome, can be async (Promise).[arguments]- Arguments to pass to the function
Example
await chromeless.evaluate(() => {
// this will be executed in Chrome
const links = [].map.call(
document.querySelectorAll('.g h3 a'),
a => ({title: a.innerText, href: a.href})
)
return JSON.stringify(links)
})
inputValue(selector: string): Chromeless
Get the value of an input field.
Arguments
selector- DOM input element
Example
await chromeless.inputValue('input#searchField')
exists(selector: string): Chromeless
Test if a DOM element exists in the document.
Arguments
selector- DOM element to check for
Example
await chromeless.exists('div#ready')
screenshot(selector: string, options: ScreenshotOptions): Chromeless
Take a screenshot of the document as framed by the viewport or of a specific element (by a selector). When running Chromeless locally this returns the local file path to the screenshot image. When run over the Chromeless Proxy service, a URL to the screenshot on S3 is returned.
Arguments
selector- DOM element to take a screenshot of,options- An options object with the following propsoptions.filePath- A file path override in case of working locallyoptions.omitBackground- Boolean to remove default white background
Examples
const screenshot = await chromeless
.goto('https://google.com/')
.screenshot()
console.log(screenshot) // prints local file path or S3 URL
const screenshot = await chromeless
.goto('https://google.com/')
.screenshot('#hplogo', { filePath: path.join(__dirname, 'google-logo.png') })
console.log(screenshot) // prints local file path or S3 URL
const screenshot = await chromeless
.goto('https://google.com/')
.screenshot({ filePath: path.join(__dirname, 'google-search.png') })
console.log(screenshot) // prints local file path or S3 URL
pdf(options?: PdfOptions) - Chromeless
Print to a PDF of the document as framed by the viewport. When running Chromeless locally this returns the local file path to the PDF. When run over the Chromeless Proxy service, a URL to the PDF on S3 is returned.
Requires that Chrome be running headless-ly. More
Arguments
options- An object containing overrides for printToPDF() parameters
Example
const pdf = await chromeless
.goto('https://google.com/')
.pdf({landscape: true})
console.log(pdf) // prints local file path or S3 URL
html(): Chromeless
Get full HTML of the loaded page.
Example
const html = await chromeless
.setHtml('<h1>Hello world!</h1>')
.html()
console.log(html) // <html><head></head><body><h1>Hello world!</h1></body></html>
cookies(): Chromeless<Cookie[] | null>
Returns all browser cookies for the current URL.
Example
await chromeless.cookies()
cookies(name: string): Chromeless<Cookie | null>
Returns a specific browser cookie by name for the current URL.
Arguments
name- Name of the cookie to get
Example
const cookie = await chromeless.cookies('creepyTrackingCookie')
cookies(query: CookieQuery) - Not implemented yet
Not implemented yet
allCookies(): Chromeless<Cookie[]>
Returns all browser cookies. Nam nom nom.
Example
await chromeless.allCookies()
setCookies(name: string, value: string): Chromeless
Sets a cookie with the given name and value.
Arguments
name- Name of the cookievalue- Value of the cookie
Example
await chromeless.setCookies('visited', '1')
setCookies(cookie: Cookie): Chromeless
Sets a cookie with the given cookie data; may overwrite equivalent cookies if they exist.
Arguments
cookie- The cookie data to set
Example
await chromeless.setCookies({
url: 'http://google.com/',
domain: 'google.com',
name: 'userData',
value: '{}',
path: '/',
expires: 0,
size: 0,
httpOnly: false,
secure: true,
session: true,
})
setCookies(cookies: Cookie[]): Chromeless
Sets many cookies with the given cookie data; may overwrite equivalent cookies if they exist.
Arguments
url- URL to navigate to
Example
await chromeless.setCookies([
{
url: 'http://google.com/',
domain: 'google.com',
name: 'userData',
value: '{}',
path: '/',
expires: 0,
size: 0,
httpOnly: false,
secure: true,
session: true,
}, {
url: 'http://bing.com/',
domain: 'bing.com',
name: 'userData',
value: '{}',
path: '/',
expires: 0,
size: 0,
httpOnly: false,
secure: true,
session: true,
}
])
deleteCookies(name: string) - Not implemented yet
Delete a specific cookie.
Arguments
name- name of the cookie
Example
await chromeless.deleteCookies('cookieName')
clearCookies(): Chromeless
Clears all browser cookies.
Example
await chromeless.clearCookies()
clearInput(selector: string): Chromeless
Clear input text.
Example
await chromeless.clearInput('#username')
setFileInput(selector: string, files: string | string[]): Chromeless
Set file(s) for selected file input.
Currently not supported in the Proxy. Progress tracked in #186
Example
await chromeless.setFileInput('.uploader', '/User/Me/Documents/img.jpg')