简体   繁体   中英

How do I check if a Google Site exists?

Does anyone know how to check if a Google Site exists?

I am trying to use var site = SitesApp.createSite(domain, siteName, name, summary); to create a new site. However, if the site (read URL) already exists, it throws an error.

I then tried to use var test = SitesApp.getSiteByUrl('https://sites.google.com/a/' + domain + '/' + siteName); to check to see if the Site exists, but it will throw an error if it does not exist.

The end result that I would like would be to:

  1. Check if Site exists.
  2. If it exists, modify site name (ie. add '1') to the end of it, and check again.
  3. Create Site

I have two possible solutions, but I am not thrilled with either of them. Both of them would run within a while loop that would continue until a url that does not exist is found.

Solution 1 Use try/catch to run SitesApp.getSiteByUrl() .

Solution 2 Use try/catch with UrlFetchApp.fetch(url).getResponseCode() . Check to see if it returns '200 OK'. If not, attempt to get the location from the header using getHeaders() and then parse it for 'WebspaceNotFound'. Unfortunately, I can't rely on the response code alone, since a non-existent site and a site that requires you to log on both report as '302 Moved Temporarily'.

Is there an easy work around for this? Do either of my solutions sound better than the other?

Because you can get the list of all sites in the domain you can do something like this:

function siteExists(domain, siteName) {
  var sites = SitesApp.getSites(domain);
  sites.forEach(function(n, i, a){a[i] = n.getName()});

  if(~sites.indexOf(siteName)) return true;
  else return false;
}

Note that if you have really lots of sites, you might need to make several getSites calls. Also I don't know how this will work when you don't have access to all the sites, since I tested from admin account. Hope it'll point you in good direction.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM