您可以使用UrlFetchApp.fetch 来尝试使用不同协议访问不同的URL,指定参数followRedirects: false。然后,您将检查 HTTP 响应代码(请参阅 getResponseCode()),如果它是可接受的响应代码,则返回 URL:
function returnFullURL(domain) {
const options = ["https://","http://", "www.", "https://www.", "http://www.", ""]; // Possible protocols, change if necessary
const badCodes = [404,301,302,303,307,308]; // Acceptable response codes, change if necessary
for (let i = 0; i < options.length; i++) {
const url = options[i] + domain;
try {
const params = {
muteHttpExceptions: true,
followRedirects: false
}
const response = UrlFetchApp.fetch(options[i] + domain, params);
const code = response.getResponseCode();
if (!badCodes.includes(code)) return url;
} catch (err) {
console.log(err);
}
}
return "No combination allowed";
}
然后您可以将其用作Custom function:
注意:
- 我不确定这些是否是要检查的适当 HTTP 响应状态代码,以及这些是否是协议、www 子域等的所有可能性,但这应该可以让您开始。
编辑:
作为替代方案,您可以通过一次调用您的函数来构建所有 URL,而不是为每个域调用它。为此,请复制并调用以下函数并指定所有域的范围(在您的示例表中,这将是 =returnAllURLs(A2:A18)):
function returnAllURLs(domains) {
const options = ["https://","http://", "www.", "https://www.", "http://www.", ""]; // Possible protocols, change if necessary
const badCodes = [404,301,302,303,307,308]; // Acceptable response codes, change if necessary
return domains.map(domain => {
for (let i = 0; i < options.length; i++) {
const url = options[i] + domain[0];
try {
const params = {
muteHttpExceptions: true,
followRedirects: false
}
const response = UrlFetchApp.fetch(options[i] + domain[0], params);
const code = response.getResponseCode();
if (!badCodes.includes(code)) return [url];
} catch (err) {
console.log(err);
}
}
return ["No combination allowed"];
});
}
相关: