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

Evaluate and rimraf... take two! #110

Merged
merged 2 commits into from
Jul 31, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions docs/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -276,10 +276,10 @@ await chromeless.viewport(1024, 800)

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

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__
Expand Down
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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"
},
Expand Down
28 changes: 26 additions & 2 deletions src/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -134,12 +134,36 @@ export async function evaluate<T>(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<void> {
Expand Down