Validate Links in JavaScript with Dead-or-Alive Library

Category: Javascript , Recommended | November 6, 2023
Author:wooorm
Views Total:34 views
Official Page:Go to website
Last Update:November 6, 2023
License:MIT

Preview:

Validate Links in JavaScript with Dead-or-Alive Library

Description:

A tiny and fast JS library for checking if URLs are alive or dead.

As developers, we often need to validate links on our sites to avoid frustrations for users. Dead links can damage credibility and user experience. With dead-or-alive, you can easily build a link checker right in your JavaScript code.

This library works across browsers, Node.js, web workers, and more. It follows redirects and checks if anchor tags point to elements on the page. The code is configurable for performance by adjusting retries and timeouts.

Basic usage:

1. Install & download.

# NPM
$ npm i dead-or-alive

2. Import the Dead-or-Alive module.

// ES
import {deadOrAlive} from 'dead-or-alive'
// Browser
<script type="module">
  import {deadOrAlive} from 'https://esm.sh/dead-or-alive@1?bundle'
</script>

3. Check if a url is dead or alive using the deadOrAlive() API.

deadOrAlive('/path/to/url/')
/*
=>
{
  "messages": [
    {
      "cause": {},
      "fatal": true,
      "message": "Unexpected error fetching `/path/to/url/`",
      "name": "1:1",
      "reason": "Unexpected error fetching `/path/to/url/`",
      "ruleId": "fetch",
      "source": "dead-or-alive",
      "url": "https://github.com/wooorm/dead-or-alive#fetch"
    }
  ],
  "status": "dead"
}
*/

4. Available options.

deadOrAlive('/path/to/url/', {
  // allowed anchors
  anchorAllowlist: [],
  // whether to check anchor links
  checkAnchor: true,
  // whether to follow HTML redirects
  followMetaHttpEquiv: true,
  // whether to find URLs in the final resource
  findUrls: true,
  // max number of redirects
  maxRedirects: 5,
  // max number of retries
  maxRetries: 1,
  // whether to accept user-content- prefix in id on elements
  resolveClobberPrefix: true,
  // timeout in milliseconds
  timeout: 3000,
  // custom user agent
  userAgen: 'Mozilla/5.0 … Safari/537.36',
  /* 
    export function defaultSleep(retries) {
      return retries ** 3 * 1000
    }
  */
  sleep: defaultSleep,
})

You Might Be Interested In:


Leave a Reply