How to parse URLs in Google Apps Script?
Asked Answered
L

2

6

I have a GAS project and I need to parse some URLs into their hostname and pathname properties as follows.

Code.gs
const url = new URL( 'http://www.example.com/cats', );
const { hostname,  pathname, } = url;

Here are some docs on the above URL constructor method. [1] | [2]

The above code produces the following error.

Error message:

ReferenceError: URL is not defined (line 64, file "Code")

What am I missing? How can I parse my URLs using GAS?

Lisandralisbeth answered 31/5, 2020 at 18:44 Comment(4)
what is your requirement exactly? your syntax is clearly incorrect but don't know what's the value of each variable like link, hostname, pathname? the URL syntax should const url = new URL(link);Penguin
@Kedar: If you are referring to the trailing comma when you cite my syntax, you should be aware that trailing commas have been supported since ECMAScript 5 for object literals and ECMAScript 2017 for function parameters. They are the preferred syntax as it makes version control diffs cleaner and less trouble editing code because you can add new properties without modifying previous lines that already use a trailing comma.Lisandralisbeth
No, I wasn't referring to trailing comma, that's fine in GAS but not the use of URL as it is not valid ECMA/script standard but part of web api. The same reason, why you can't do console.log in GAS. Instead add fetch for URI.js in .gs and then... const url = URI( 'example.com/cats', );Penguin
@Kedar: If it's different from this answer, please consider adding an answer that explains how you would recommend to add fetch for URI.js in .gsLisandralisbeth
L
3

This article explains how to implement the URI.js library into a Google Apps Script project.

URIjs.gs

eval(UrlFetchApp.fetch('https://cdnjs.cloudflare.com/ajax/libs/URI.js/1.19.11/URI.min.js').getContentText());

// Get the URL protocol (eg. 'https' or 'http')
function urlProtocol(url){
  return URI(url).protocol()
}
  
// Get the URL hostname (eg. 'googleappscripting.com')
function urlHostname(url){
  return URI(url).hostname()
}

// Get the whole URL path (eg. '/some/directory/filename.png')
function urlPath(url){
  return URI(url).path()
}

// Get the URL directory (eg. '/some/directory')
function urlDirectory(url){
  return URI(url).directory()
}
    
// Get the URL file name (eg. 'filename.png')
function urlFilename(url){
  return URI(url).filename()
}

// Get the URL query string (eg. 'this=1&that=2')
// If a query string parameter is provided as the second argument
// then the function will return the value of that parameter
function urlQuery(url,param){
  if (param !== undefined){
    var queryMap = URI(url).query(true);
    return queryMap[param]
  }
  return URI(url).query()
}

// Get the URL hash (eg. '#section-two')
function urlHash(url){
  return URI(url).hash()
}

// Check to see if a URL is a fully qualified URL
function urlIsUrl(url){
  return URI(url).is('url')
}

// Check to see if a URL is a fully qualified IP Address
function urlIsIp(url){
    return URI(url).is('ip')
}


// Test function to ensure that each of the above functions do what they are supposed to do.
function testURI() {

  var testUrl = 'https://googleappscripting.com/some/test/page.html?this-is=helpful&it=works#rad';  
  var funcTests = [
    urlProtocol,
    urlHostname,
    urlDirectory,
    urlPath,
    urlFilename,
    urlQuery,
    urlHash,
    urlIsUrl,
    urlIsIp
  ]
  
  // Check that each function returns the expected value
  funcTests.forEach(function(test){
    Logger.log(test(testUrl))
  });
  
  // Extra check to see that the urlQuery function works with a query parameter argument
  Logger.log(urlQuery(testUrl,'it'));

}

Then in my code, as follows:

Code.gs

const hostname = URIjs.urlHostname( 'http://www.example.com/cats', );
Lisandralisbeth answered 1/6, 2020 at 2:49 Comment(1)
2023 update: rawgit.com is discontinued. cdnjs.cloudflare.com can be used as a drop-in replacement: eval(UrlFetchApp.fetch('https://cdnjs.cloudflare.com/ajax/libs/URI.js/1.19.11/URI.min.js').getContentText());Nath
F
1

The URL interface is not part of ECMAScript, it's part of a Web API, more specifically of URL API. Google Apps Script doesn't support web APIsm by default.


From https://developers.google.com/apps-script/guides/v8-runtime

Modern ECMAScript syntax

You can use modern ECMAScript syntax in scripts that are powered by the V8 runtime. This syntax includes let, const, and many other popular features.

Related

Fifield answered 31/5, 2020 at 21:21 Comment(1)
Downvoted, because this answer only says what the person is doing wrong, and doesn't answer the question: How to parse URLs in Google Apps Script?Apothecary

© 2022 - 2024 — McMap. All rights reserved.