How to Use Google Docs as a Code Runner
There is a way to use Google Docs as a programming IDE and run JavaScript code inside the editor.
You have been using Google Docs to write documents and essays but did you know that the same editor can also be used to write and run JavaScript code?
It is no replacement for a dedicated IDE like Visual Studio code but Google Docs can be used as a JavaScript playground to quickly run code snippets.
Here’s a sample document written in Google Docs and the document body contains a JavaScript function that calculates the number of days left until the next Christmas.
Go to the Code Runner
menu, choose Run JavaScript
and the output of the function will display in a popup. See demo
Code Runner in Google Docs
Internally, there’s a little Google Apps Script that is doing the magic. It reads the body of your Google Document as a text string and uses the eval()
function of JavaScript to evaluate the text.
/**
* @OnlyCurrentDoc
*/
function codeRunner() {
const doc = DocumentApp.getActiveDocument();
const text = doc.getBody().getText();
const response = eval(text);
DocumentApp.getUi().alert(response);
}
function onOpen() {
const ui = DocumentApp.getUi();
const menu = ui.createMenu('Code Runner');
menu.addItem('🦄 Run JavaScript ', 'codeRunner');
menu.addToUi();
}
Related reading:
Amit Agarwal
Google Developer Expert, Google Cloud Champion
Amit Agarwal is a Google Developer Expert in Google Workspace and Google Apps Script. He holds an engineering degree in Computer Science (I.I.T.) and is the first professional blogger in India.
Amit has developed several popular Google add-ons including Mail Merge for Gmail and Document Studio. Read more on Lifehacker and YourStory