In order to be GDPR compliant I wrapped all affiliate scripts on our webshop inside functions and add them to a job queue.
After the user accepts our privacy policy I run all queued jobs. I want to run them in global scope so all declared variables are accessible in global scope because some affiliate scripts are depending on global variables (I know that’s ugly 😉 ).
I know, I could rewrite all the javascript code and declare the varibales in global scope and wrap the rest of the code inside a function.
But then I would need to edit a lot of external modules (we are running a magento webshop and use external modules for including the affiliate scripts)
my current approach:
var jobQueue = [];
var add = function (fn) {
jobQueue.push(fn);
console.log("function pushed to queue");
};
var execute = function () {
while ((curJob = jobQueue.pop()) !== undefined) {
curJob();
console.log("executed job");
}
};
my problem is that some external scripts are depending on the variables declared inside my jobs. Is there any possibility to run the functions like the code was run globally?
I already found something like this but I could not make it work:
Javascript eval on global scope?
(this does not work with functions)
eval.call(window, x, y, z)
2
Answers
I found a possible solution but it is ugly:
I save the body of the function (How to get function body text in JavaScript?) to a string and evaluate it in window scope
Variables in Javascript have ‘function scope’, meaning that if you declare a variable inside a function, it won’t be accessible from outside that function.
But when a variable doesn’t exist inside a function, Javascript will look for that variable outside that function until it reaches the global object.
So variables declared in the global object are visible everywhere.
You can assign variables to the global scope just by declaring them in the global scope.
JS Bin
As you can see, the job added has access to the variable jobTitle that is declared in the global scope.
Hope it helps