1

I have a Google Sheets on a GSuite Drive that I own. This Google Sheets has a bound code.js script file. I also have a remote .js file that contains the function I want to execute on my sheet (in a normal situation this function would simply reside within the code.js file).

I have created button images on the sheet that trigger scripts inside the code.js file. When I click a button my code.js script executes successfully:

  • the button triggers the code.js script which fetches the remote js file via URL and stores it into a variable (this remote file could just as easily be a text file but to keep my OCD in check I named it .js)
  • I use console.log(variable) to confirm that indeed the entire.js file has been retrieved.
  • I use eval(variable) but nothing happens

If I paste the console.log(variable) output directly into the code.js file, it works as expected.

Is eval() the wrong call? Or is it not as powerful as I am hoping?

function countStuffButton() { //Counts the number of current stuffs
    var url = "http://my.website/js/countStuff.js";
    var javascript = UrlFetchApp.fetch(url).getContentText();
    console.log(javascript);
    eval(javascript);  
}

console.log that I get back:

function countStuff() {
    // bunch of code that works when paste directly into code.js
}

What I am hoping/expecting is that I can store a JavaScript function on a server in a .js file and then fetch the content of the function to be processed locally within the code.js bound script of my Google Sheets, resulting in a Google Sheets that is a pure "front end" making script and HTML calls to files that I fully own and control on my server.

pnuts
  • 54,806
  • 9
  • 74
  • 122
Dave
  • 75
  • 10

1 Answers1

1

The eval(code) function you know it executes JavaScript code from a string.

However code needs to be a string that contains the JavaScript expression to be evaluated or the statements to be executed.

In your case the variable javascript contains the countStuff function declaration.

Function declarations are statements as they perform the action of creating a variable whose value is that of the function.

To fix that you can:

  1. Change your remote countStuff function to become an immediately-invoked Function Expression :
function countStuff() {
//bunch of code that works when paste directly into code.js
}()
  1. Invoke the function yourself eval('new ' + javascript + '()')

To understand this second scenario and why new is needed have a look at this answer.

  1. countStuff becomes available so you can also call it after eval()'s execution like countStuff()
Laurentiu L.
  • 6,213
  • 1
  • 28
  • 55