6

Web Tools #548 - URL.canParse(), Web Frameworks, Git/CLI Tools, Vue Tools

 7 months ago
source link: https://mailchi.mp/webtoolsweekly/web-tools-548
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

URL.canParse(), Web Frameworks, Git/CLI Tools, Vue Tools

Issue #548 • January 18, 2024

Advertisement

Build with the Power of Code — Without Writing Any Take control of HTML, CSS, and JavaScript in a visual canvas.

Webflow

Webflow generates clean, semantic code that’s ready to publish or hand to developers.

Start Building →

In case you didn't know, there's a URL interface that exposes a number of different properties and methods for dealing with URLs in the browser. One relatively new method that now has almost cross-browser support in all modern browsers is the URL.canParse() method.

This method allows you to check if a URL (absolute or relative) is valid and able to be parsed, returning a Boolean to indicate as much. The method takes one required parameter that can be either a string or an object that has a built in stringifier (i.e. a feature that automatically converts the object to a string when a string is expected). It also accepts a second optional parameter that represents a base URL for when the URL you're checking is a relative one.

Here are some examples:

URL.canParse("https://webtoolsweekly.com"); // true
URL.canParse("/about"); // false
URL.canParse("/about", "https://webtoolsweekly.com"); // true
URL.canParse(document.querySelector('a')); // true

Notice the middle two lines are both checking a relative URL. But only the second one returns true because the first one doesn't provide a base. The last line checks an object (in this case a reference to an anchor element on the page). This assumes there is at least one anchor element present, otherwise it would return false.

Of course, in the flow of a real application, you wouldn't be dropping literal values into these parameters but you might be constructing a URL dynamically, thus requiring that you check them for validation before doing anything with the URLs.

Some things to keep in mind when using this method:

  • If you provide a base with an absolute URL, the base will be ignored
  • Since there's a little bit of browser support lacking, you can check if the method exists using if ("canParse" in URL) { ... }
  • The method returns true for the same values valid in a URL() constructor and false for values that would cause the constructor to fail.

You can try out my examples in this CodePen demo, which has al link on the page to ensure the fourth line works as expected.

Now on to this week's tools!


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK