Programmatically submitting Google Forms with AngularJs

Google Forms is a viable way to do business. We’ve seen a few successful compaines that rely on it for day-to-day operations. The flow would normally involve users entering data on the go and someone at the back office analysing the responses with Google Spreadsheet.

Forms are flexible

One huge selling point if that we can design our own forms for all kinds of situations: racing bets, work time/attendance, baby feeding – we’ve seen a few exotic cases. Static form data is not enough, we can opt for Google Apps script.

One thing remains the same though

Look and feel of Google forms and default validations do leave much to be desired. What if there was a way to Swap the form UI out for a custom branded SPA with fancy lookaheads and what not?

There is a way

Surely, it all starts with making a form. We’ll go to google forms are design a new one. Expect to spend some time getting it right for your needs. For purposes of this demo we’ll be submitting a table (we’d cheat a bit and post JSON only though).

We’d also ensure that answers get submitted into a new spreadsheet:

Now we need to grab field names Google generated for a form (it is a simple HTML form after all!). Open up form preview, and go to dev tools console in the new tab

And run the following snippet in the console and note the outputs:

document.querySelectorAll('form').forEach((x) => {console.log(x.action)});
document.querySelectorAll('[name^="entry."]').forEach((x) => {console.log(x.name + '=' + x.closest('[role="listitem"]').querySelector('[role="heading"]').innerText)})

Oh, and one more thing…

Well, we’ve got the fields, but to succesfully submit the it we need to know where to submit to. Apparently, it’s a simple matter of picking up the form Id and crafting a URL: https://docs.google.com/forms/d/<your id here>/formResponse

And we are done…almost

Dissecting Google forms was fun. Now we need to somehow build our own frontend to the form. For our specific use case we wanted to show off how we would go about submitting a table dynamically populated with content. As I’ve got a soft spot for AngularJs, I figured I might as well got for it.

Building a custom form

There’s plenty of resources online on how to build SPAs, so I’d not elaborate much on that. There’s however a couple of considerations that in my opinion will make the form submission process seamless for an SPA experience. First and foremost – we’d like to stay on the same page when forms gets sent away – we’d also like to get notified when form gets submitted so our SPA can take own action. One way to do it is to submit a from into a hidden iframe and use its onLoad event to report back (that’s the method I ended up implementing in the example snippet).

Talk is cheap, show me the code

Working example of this technique can be found here: https://codepen.io/timur_kh/pen/oNXYNdL