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

夙愿已清 提交于 2019-11-28 10:28:58

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

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!