Skip to content

Commit

Permalink
Merge pull request #1213 from searchspring/getcontext-vars
Browse files Browse the repository at this point in the history
Auto-eval `getContext`
  • Loading branch information
korgon authored Dec 4, 2024
2 parents bae1305 + 2f3207e commit e414bd0
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 3 deletions.
26 changes: 25 additions & 1 deletion packages/snap-toolbox/src/getContext/getContext.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,17 @@
import { getContext } from './getContext';

describe('getContext', () => {
beforeEach(() => (document.body.innerHTML = ''));
beforeAll(() => {
// used to test global variable assignment in evaluation
const globalScriptTag = document.createElement('script');
globalScriptTag.innerHTML = 'const globalVar = "constant";';

document.head.append(globalScriptTag);
});

beforeEach(() => {
document.body.innerHTML = '';
});

it('expects an array of strings as the first parameter', () => {
const scriptTag = document.createElement('script');
Expand Down Expand Up @@ -261,4 +271,18 @@ describe('getContext', () => {
getContext(['error'], scriptTag);
}).toThrow();
});

it('does not throw an error when variables exist already, but are not in evaluation list', () => {
const scriptTag = document.createElement('script');
scriptTag.setAttribute('type', 'searchspring/recommend');
scriptTag.setAttribute('id', 'searchspring-recommend');
scriptTag.innerHTML = `
siteId = 'abc123';
globalVar = 'snap';
`;

expect(() => {
getContext(['error'], scriptTag);
}).not.toThrow();
});
});
15 changes: 13 additions & 2 deletions packages/snap-toolbox/src/getContext/getContext.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,12 +46,23 @@ export function getContext(evaluate: string[] = [], script?: HTMLScriptElement |
});

const scriptVariables: ContextVariables = {};
const scriptInnerHTML = scriptElem.innerHTML;

// attempt to grab inner HTML variables
const scriptInnerVars = scriptInnerHTML.match(/([a-zA-Z_$][a-zA-Z_$0-9]*)\s?=/g)?.map((match) => match.replace(/[\s=]/g, ''));

const combinedVars = evaluate.concat(scriptInnerVars || []);

// de-dupe vars
const evaluateVars = combinedVars.filter((item, index) => {
return combinedVars.indexOf(item) === index;
});

// evaluate text and put into variables
evaluate?.forEach((name) => {
const fn = new Function(`
var ${evaluate.join(', ')};
${scriptElem.innerHTML}
var ${evaluateVars.join(', ')};
${scriptInnerHTML}
return ${name};
`);

Expand Down

0 comments on commit e414bd0

Please sign in to comment.