Disclaimer: I fully understand the risks/downsides of using eval but this is one niche case where I couldn't find any other way.
In Google Apps Scripting, there still is no built-in capability to import a script as a library so many sheets can use the same code; but, there is a facility built-in where I can import text from a plaintext file.
Here's the eval-ing code:
var id = [The-docID-goes-here];
var code = DocsList.getFileById(id).getContentAsString();
var lib = eval(code);
Logger.log(lib.fetchDate());
Here's some example code I'm using in the external file:
{
fetchDate: function() {
var d = new Date();
var dateString = (d.getMonth() + 1) + "/" + d.getDate() + "/" + d.getFullYear();
return dateString;
}
}
What I'm aiming for is to drop a big object literal (containing all the library code) onto a local variable so I can reference it's properties/functions like they're contained in their own namespace.
`Function() is a faster and more secure alternative to eval().
Malicious code : invoking eval can crash a computer. For example: if you use eval server-side and a mischievous user decides to use an infinite loop as their username. Terribly slow : the JavaScript language is designed to use the full gamut of JavaScript types (numbers, functions, objects, etc)… Not just strings!
The eval() function in JavaScript is used to evaluate the expression. It is JavaScirpt's global function, which evaluates the specified string as JavaScript code and executes it. The parameter of the eval() function is a string. If the parameter represents the statements, eval() evaluates the statements.
Replace var lib = eval(code);
with:
var lib = eval('(' + code + ')');
When the parens are omitted, the curly braces are being interpreted as markers of a block of code. As a result, the return value of eval
is the fetchData
function, instead of a object containing the function.
When the function name is missing, the code inside the block is read as a labelled anonymous function statement, which is not valid.
After adding the parens, the curly braces are used as object literals (as intended), and the return value of eval
is an object, with the fetchData
method. Then, your code will work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With