diff --git a/packages/snap-toolbox/src/getContext/getContext.test.ts b/packages/snap-toolbox/src/getContext/getContext.test.ts index 2cdb794ad..6c76d01ff 100644 --- a/packages/snap-toolbox/src/getContext/getContext.test.ts +++ b/packages/snap-toolbox/src/getContext/getContext.test.ts @@ -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'); @@ -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(); + }); }); diff --git a/packages/snap-toolbox/src/getContext/getContext.ts b/packages/snap-toolbox/src/getContext/getContext.ts index 8a32517a0..f55304f90 100644 --- a/packages/snap-toolbox/src/getContext/getContext.ts +++ b/packages/snap-toolbox/src/getContext/getContext.ts @@ -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}; `);