简体   繁体   English

如何检查Google网站是否存在?

[英]How do I check if a Google Site exists?

Does anyone know how to check if a Google Site exists? 有谁知道如何检查Google网站是否存在?

I am trying to use var site = SitesApp.createSite(domain, siteName, name, summary); 我正在尝试使用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. 但是,如果站点(读取URL)已经存在,则会引发错误。

I then tried to use var test = SitesApp.getSiteByUrl('https://sites.google.com/a/' + domain + '/' + siteName); 然后,我尝试使用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. 如果存在,请在其末尾修改站点名称(即添加“ 1”),然后再次检查。
  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. 它们都将在while循环内运行,该循环将继续直到找到不存在的url。

Solution 1 Use try/catch to run SitesApp.getSiteByUrl() . 解决方案1使用try / catch运行SitesApp.getSiteByUrl()

Solution 2 Use try/catch with UrlFetchApp.fetch(url).getResponseCode() . 解决方案2将try / catch与UrlFetchApp.fetch(url).getResponseCode() Check to see if it returns '200 OK'. 检查是否返回“ 200 OK”。 If not, attempt to get the location from the header using getHeaders() and then parse it for 'WebspaceNotFound'. 如果不是,请尝试使用getHeaders()从标头中获取位置,然后将其解析为“ 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'. 不幸的是,我不能仅依靠响应代码,因为不存在的站点和要求您以“ 302临时移动”的身份登录两个站点的站点。

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. 请注意,如果您确实有很多站点,则可能需要调用几个getSites。 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. 希望它将为您指明方向。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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