Programmatically edit a Google doc with JavaScript

Josh picture Josh · Jun 15, 2012 · Viewed 7k times · Source

What I'm trying to do is run some JavaScript code that will enter text into a Google doc. What I have done so far is create an iframe element on my personal web page that embeds Google Docs. What I want to do, for now, is use functions from Google's source code to input the text.

When I use the Chrome inspector along with a js beautifier, I found that if I listen for a keypress event, I get brought to the following code segment:

function dKa() {
   var a = eKa, b = TJa ? function(c) {
      return a.call(b.src, b.key, c)
   } : function(c) {
      c = a.call(b.src, b.key, c);
      if (!c)
      return c
   };
   return b
}

I have tried calling the function upon loading the page with a simple onload="function();" event in a futile attempt to yield an output, but nothing happened. Is there a way to do what I'm trying to do? I want find the correct function to call, so that I may write text to the doc via that funcion. However, the code seems too obfuscated to do anything with.

I know that to refer to the Google Docs (the iframe) code from the parent frame, I need to do the following: document.getElementById("iframeID").contentWindow.theFunction() Am I wrong in my execution? To my knowledge, it isn't possible to live edit a Google Doc using their API.

This is also my first time posting here, so if this is too vague, let me know and hopefully I can clarify. Thanks in advance.

Answer

Jordan Running picture Jordan Running · Jun 15, 2012

As others have noted the same-origin policy will prevent the approach you're taking from working, and trying to reverse-engineer it is folly anyway as the implementation could change at any time (or even be different for different users as Google rolls out updates).

However, Google has an API for this exact thing called Google Apps Script. Most of the tutorials are geared toward spreadsheets, but there is documentation for DocumentApp, DocsList, Document, etc. You may have to rethink your approach a bit but you should still be able to accomplish your goals.