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.
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.
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.