Search code examples
javascriptjquerygoogle-apps-scriptgoogle-sites

Access Google App Functions in jquery/javascript


I am using google app scripts on google sites. I have created a navigation menu, and I embedded it into the page. I want to get the pageURL() from google scripts and retrieve it in my JavaScript page. I tried using the scriptlet to get the value, but it doesn't execute. Here is what I have so far. How can I get access to values in google app scripts and use them in my JavaScript function?

google script (.gs)

 function getPageName(){
    var site = SitesApp.getSite("site.com", "sitename");
    var page = site.getChildren()[0];
    var pageName = page.getUrl().split("/").splice(-1)[0];
    return pageName;
 }

javascript file

var pageName =  <?!= getPageName()?>; // doesnt execute, need to get page url
if(pageName == linkName){
 // add class here. 
}

Since google loads the apps script as an iframe, I tried doing window.location.href, but it doesn't work either. The page name ends up being the name of the google app instead.


Solution

  • An alternative to using scriptlets is to use google.script.run (Client-side API)

    It's pretty easy to use. In your case, it should be like this

    code.gs

    function getPageName(){
        var site = SitesApp.getSite("site.com", "sitename");
        var page = site.getChildren()[0];
        var pageName = page.getUrl().split("/").splice(-1)[0];
        return pageName;
     }
    

    Javascript File:

    function onSuccess(receviedPageName)
    {
        if(receviedPageName== linkName)
        {
         // add class here. 
        }
    }//onSuccess
    google.script.run.withSuccessHandler(onSuccess).getPageName();
    

    withSuccessHandler(function) is executed if the server-side function returns successfully or withFailureHandler(function) is executed if a server side function fails to complete the task it was assigned.

    Give it a try :)