Skip to content

Commit

Permalink
executeFunction: throw error when passing native functions (#18)
Browse files Browse the repository at this point in the history
  • Loading branch information
fregante authored Jan 25, 2023
1 parent 7078254 commit 0ec3d36
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 2 deletions.
10 changes: 8 additions & 2 deletions index.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
/* eslint-disable @typescript-eslint/consistent-type-assertions */
import {chrome} from 'jest-chrome';
import {describe, it, assert} from 'vitest';
import {getTabsByUrl} from './index.js';
import {describe, it, assert, expect} from 'vitest';
import {executeFunction, getTabsByUrl} from './index.js';

const tab1 = {
id: 1,
Expand Down Expand Up @@ -66,3 +66,9 @@ describe('getTabsByUrl', () => {
);
});
});

describe('executeFunction', () => {
it('should throw with native functions', async () => {
await expect(executeFunction(1, Date)).rejects.toMatchInlineSnapshot('[TypeError: Native functions need to be wrapped first, like `executeFunction(1, () => alert(1))`]');
});
});
6 changes: 6 additions & 0 deletions index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,11 +49,17 @@ function castArray<A = unknown>(possibleArray: A | A[]): A[] {

type MaybeArray<X> = X | X[];

const nativeFunction = /^function \w+\(\) {[\n\s]+\[native code][\n\s]+}/;

export async function executeFunction<Fn extends (...args: any[]) => unknown>(
target: number | Target,
function_: Fn,
...args: unknown[]
): Promise<ReturnType<Fn>> {
if (nativeFunction.test(String(function_))) {
throw new TypeError('Native functions need to be wrapped first, like `executeFunction(1, () => alert(1))`');
}

const {frameId, tabId} = castTarget(target);

if (gotScripting) {
Expand Down

0 comments on commit 0ec3d36

Please sign in to comment.