Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically edit a Google doc with JavaScript

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.

like image 626
Disco Globeulon Avatar asked Jun 15 '12 19:06

Disco Globeulon


People also ask

Can you run JavaScript in Google Docs?

If you're comfortable with JavaScript, you can write your own original programs. Just open Docs or Sheets and go to Extensions, then click on Apps Script. A new tab with the Apps Script editor interface will open. There, you can create new scripts or run existing ones (use the Run button on the toolbar).

Can commenters edit on Google Docs?

You can collaborate with others on Google Docs, Sheets, and Slides to: Add, edit, reply, or delete comments.

Does Google Docs use Contenteditable?

Google Docs uses its own editing surface instead of contenteditable. It draws its own selection and caret and handles most key and mouse events manually.


1 Answers

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.

like image 185
Jordan Running Avatar answered Sep 18 '22 10:09

Jordan Running