Google Apps Script And Getting Site Context

Knoldus Inc.
Knoldus - Technical Insights
2 min readJul 31, 2011

Google Script UI services enables to create rich UI in Google Sites. There is a bug where there is no way to find out directly where Google Apps Script is embedded in Sites. If you are faced with similar dilemma and need a workaround read on. This a critical issue when a script intended to be executed for multiple sites.

In our case the requirement was to fetch the data for site instances from the spreadsheet. Site instances were created from a template Site. The template Site containing the apps script required to know the active site, or in other words the UI apps script required to know the context of the site it is embedded in.

There is an existing method SitesApp.getActiveSite() which runs perfectly for the Script but fails when it is coded in Google UI Script. You can read more of it here.

The solution was suggested by Rahim where he found a way to wrap the Google Apps UI Script in a Google Widget and pass Site URL reference parameter to the UI script.

The Google Widget xml file has a reference to the published UI script url and it uses document.referrer javascript to get the URL where it is embedded in. This is how the Google Widget looks like.

[code language=”xml”]
<?xml version=”1.0" encoding=”UTF-8"?>
<Module>
<ModulePrefs title=”Company Description” />
<Content type=”html”><![CDATA[<div id=”txt”></div>
<iframe id=”gdgt” frameborder=”0" height=”100%” width=”100%”></iframe>
<script type=”text/javascript”>
document.getElementById(‘gdgt’).src=’publishedUrl&siteurl=’ + document.referrer;</script>
]]></Content>
</Module>
[/code]

If you notice the gadget you will see that publishedUrl is actually be the published UI script created on Site. Also we are passing siteurl as a parameter to the script. This way we are able to pass the reference of the Site to the apps script.

Lets now have a look at the UI Script. To keep things simple we just show a label of the Site URL.

[code language=”javascript”]
function doGet(e) {
var app = UiApp.createApplication()
var siteurl = e.parameter.siteurl
var siteUrlLabel = app.createLabel(siteurl)
app.add(siteUrlLabel)
return app
}
[/code]

The code that retrieves the URL is e.parameter.siteurl which was passed as parameter to the UI script by google gadget.

To validate that we can see the site url. We have to insert the gadget by the URL. The URL depends where have we uploaded the gadget. You can read more on it from here.

Now in order to get the actual site we just have to do string manipulation of the siteurl and call SitesApp.getSite(“sitename”)

This is a nice workaround to the problem till the issue gets resolved by google.

--

--

Knoldus Inc.
Knoldus - Technical Insights

Group of smart Engineers with a Product mindset who partner with your business to drive competitive advantage | www.knoldus.com