Skip to content
This repository was archived by the owner on Nov 24, 2018. It is now read-only.

Commit b696473

Browse files
author
Joel Griffith
authored
Merge pull request #110 from joelgriffith/feature/evaluate+build+rimraf
Evaluate and rimraf... take two!
2 parents bf4bee7 + 1b0b322 commit b696473

File tree

3 files changed

+30
-6
lines changed

3 files changed

+30
-6
lines changed

docs/api.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -276,10 +276,10 @@ await chromeless.viewport(1024, 800)
276276

277277
### evaluate<U extends any>(fn: (...args: any[]) => void, ...args: any[]): Chromeless<U>
278278

279-
Evaluate Javascript code within Chrome in the context of the DOM.
279+
Evaluate Javascript code within Chrome in the context of the DOM. Returns the resulting value or a Promise.
280280

281281
__Arguments__
282-
- `fn` - Function to evaluate within Chrome
282+
- `fn` - Function to evaluate within Chrome, can be async (Promise).
283283
- `[arguments]` - Arguments to pass to the function
284284

285285
__Example__

package.json

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,8 +19,8 @@
1919
},
2020
"scripts": {
2121
"watch": "tsc -w",
22-
"build": "rm -rf dist; tsc -d",
23-
"prepublish": "npm run build; npm test",
22+
"build": "rimraf dist; tsc -d",
23+
"prepublishOnly": "npm test; npm run build",
2424
"test": "npm run tslint",
2525
"tslint": "tslint -c tslint.json -p tsconfig.json"
2626
},

src/util.ts

Lines changed: 26 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -134,12 +134,36 @@ export async function evaluate<T>(client: Client, fn: string, ...args: any[]): P
134134
const {Runtime} = client
135135
const jsonArgs = JSON.stringify(args)
136136
const argStr = jsonArgs.substr(1, jsonArgs.length - 2)
137-
const expression = `(${fn})(${argStr})`
137+
138+
const expression = `
139+
(() => {
140+
const expressionResult = (${fn})(${argStr});
141+
if (expressionResult && expressionResult.then) {
142+
expressionResult.catch((error) => { throw new Error(error); });
143+
return expressionResult;
144+
}
145+
return Promise.resolve(expressionResult);
146+
})();
147+
`
138148

139149
const result = await Runtime.evaluate({
140150
expression,
151+
returnByValue: true,
152+
awaitPromise: true,
141153
})
142-
return result.result.value
154+
155+
if (result && result.exceptionDetails) {
156+
throw new Error(
157+
result.exceptionDetails.exception.value ||
158+
result.exceptionDetails.exception.description
159+
)
160+
}
161+
162+
if (result && result.result) {
163+
return result.result.value
164+
}
165+
166+
return null
143167
}
144168

145169
export async function type(client: Client, text: string, selector?: string): Promise<void> {

0 commit comments

Comments
 (0)