diff --git a/docs/api.md b/docs/api.md index c911269f..7a750826 100644 --- a/docs/api.md +++ b/docs/api.md @@ -276,10 +276,10 @@ await chromeless.viewport(1024, 800) ### evaluate(fn: (...args: any[]) => void, ...args: any[]): Chromeless -Evaluate Javascript code within Chrome in the context of the DOM. +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 +- `fn` - Function to evaluate within Chrome, can be async (Promise). - `[arguments]` - Arguments to pass to the function __Example__ diff --git a/package.json b/package.json index f2a183f7..a1445aef 100644 --- a/package.json +++ b/package.json @@ -19,8 +19,8 @@ }, "scripts": { "watch": "tsc -w", - "build": "rm -rf dist; tsc -d", - "prepublish": "npm run build; npm test", + "build": "rimraf dist; tsc -d", + "prepublishOnly": "npm test; npm run build", "test": "npm run tslint", "tslint": "tslint -c tslint.json -p tsconfig.json" }, diff --git a/src/util.ts b/src/util.ts index d47c0830..1b54a855 100644 --- a/src/util.ts +++ b/src/util.ts @@ -134,12 +134,36 @@ export async function evaluate(client: Client, fn: string, ...args: any[]): P const {Runtime} = client const jsonArgs = JSON.stringify(args) const argStr = jsonArgs.substr(1, jsonArgs.length - 2) - const expression = `(${fn})(${argStr})` + + const expression = ` + (() => { + const expressionResult = (${fn})(${argStr}); + if (expressionResult && expressionResult.then) { + expressionResult.catch((error) => { throw new Error(error); }); + return expressionResult; + } + return Promise.resolve(expressionResult); + })(); + ` const result = await Runtime.evaluate({ expression, + returnByValue: true, + awaitPromise: true, }) - return result.result.value + + if (result && result.exceptionDetails) { + throw new Error( + result.exceptionDetails.exception.value || + result.exceptionDetails.exception.description + ) + } + + if (result && result.result) { + return result.result.value + } + + return null } export async function type(client: Client, text: string, selector?: string): Promise {