Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

inject external javascript file in google app script(Google Docs) [closed]

Please let me know how to inject external javascript file in google app script(Google Docs).

Thanks in advance.

like image 658
Prashant Mhase Avatar asked Nov 04 '14 09:11

Prashant Mhase


2 Answers

Depending on what you mean by Inject, one possible answer is to use the standard javascript eval() function along with UrlFetchApp:

eval(UrlFetchApp.fetch('http://path.to/external/javascript.js').getContentText());

If you want to include a JS file in the HTML output of a published script, simply include the javascript using tags in your HTML.

<script src="http://path.to/external/javascript.js"></script>

Eval docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval UrlfetchApp docs: https://developers.google.com/apps-script/reference/url-fetch/url-fetch-app

like image 67
Cameron Roberts Avatar answered Nov 03 '22 00:11

Cameron Roberts


Do you expect the Javascript file you wish to "inject" to change regularly? If not, the easiest way will be to make a new script file in your project, and add the content of the file you want to inject. For instance, let's say you start with Code.gs with just one function, based heavily on the Spreadsheets project template:

/**
 * Adds a custom menu to the active spreadsheet
 */
function onOpen() {
  var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
  var entries = [{
    name : "Tell a Joke",
    functionName : "beFunny"
  }];
  spreadsheet.addMenu("Script Center Menu", entries);
};

You see I'm calling "beFunny()" which is not in this file. Instead, it's in a new file, ExtraStuff.gs:

function beFunny() {
  Browser.msgBox('Waka waka waka');
}

Run this, and the Tell a Joke menu item works, even though nothing in Code.gs refers to the existence of another script file. Instead, the functions and variables declared in of all of the files in the project are "in scope" for one another.

like image 25
Jesse Scherer Avatar answered Nov 02 '22 23:11

Jesse Scherer