1
- import _ from 'lodash' ;
2
-
3
- const makeIdent = ( ) => _ . times ( 20 , ( ) => _ . random ( 35 ) . toString ( 36 ) ) . join ( '' ) ;
1
+ const makeIdent = ( ) => Math . random ( ) . toString ( 36 ) . substring ( 2 , 10 ) ;
4
2
5
3
export default function runOnPage ( func ) {
6
4
return ( ...args ) => new Promise ( ( resolve , reject ) => {
@@ -22,15 +20,15 @@ export default function runOnPage(func) {
22
20
const serializedArgs = args . map ( x => {
23
21
if ( x instanceof Element ) {
24
22
if ( x . id ) {
25
- return { id : x . id } ;
23
+ return `document.getElementById( ${ JSON . stringify ( x . id ) } )` ;
26
24
} else {
27
25
x . id = makeIdent ( ) ;
28
- return { tempId : x . id } ;
26
+ return `(() => { const elem = document.getElementById( ${ JSON . stringify ( x . id ) } ); elem.id = ''; return elem; })()` ;
29
27
}
30
28
} else if ( typeof x === 'function' ) {
31
- return { func : x . toString ( ) } ;
29
+ return `(() => ${ x . toString ( ) } )()` ;
32
30
} else {
33
- return { val : x } ;
31
+ return JSON . stringify ( x ) ;
34
32
}
35
33
} ) ;
36
34
@@ -41,21 +39,7 @@ export default function runOnPage(func) {
41
39
const scriptContent = `
42
40
(async () => {
43
41
try {
44
- const serializedArgs = ${ JSON . stringify ( serializedArgs ) } ;
45
- const args = serializedArgs.map(x => {
46
- if ('id' in x) {
47
- return document.getElementById(x.id);
48
- } else if ('tempId' in x) {
49
- const elem = document.getElementById(x.tempId);
50
- elem.id = '';
51
- return elem;
52
- } else if ('func' in x) {
53
- const generate = new Function('return ' + x.func);
54
- return generate();
55
- } else {
56
- return x.val;
57
- }
58
- });
42
+ const args = [${ serializedArgs . join ( ',' ) } ];
59
43
const ret = await (${ serialized } )(...args);
60
44
window.postMessage({ ident: ${ JSON . stringify ( ident ) } , ret });
61
45
} catch (err) {
@@ -67,7 +51,7 @@ export default function runOnPage(func) {
67
51
` ;
68
52
69
53
const script = document . createElement ( 'script' ) ;
70
- script . innerHTML = scriptContent ;
54
+ script . text = scriptContent ;
71
55
document . documentElement . prepend ( script ) ;
72
56
} ) ;
73
57
}
0 commit comments