File/hasWebAccess.js

/**
 * An async function which determines if the current computer has internet
 * access by pinging to a server. If no url is provided it checks
 * navigator.online
 *
 * @function hasWebAccess
 * @async
 * @since 1.0.0
 * @memberof module:File
 *
 * @param {string} [url] A url to a server
 *
 * @return {promise} A promise that resolves to true or false
 * @example
 * import { hasWebAccess } from 'fenix-tools'
 *
 * const canDownload = await hasWebAccess('http://google.com')
 * console.log(canDownload) // => returns true
 *
 * hasWebAccess('http://google.com')
 * .then('Web connection is live!)
 */
export default async function hasWebAccess (url) {
  if (!url) { return navigator.onLine }
  const result = await window.fetch(url, {
    method: 'HEAD',
    cache: 'no-cache'
  }).then((response) => {
    return response.ok === true
  })
  return result
}