Skip to content

Instantly share code, notes, and snippets.

@gangsthub
Last active November 27, 2020 09:14
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gangsthub/b2efa76be5314a332cfcfd1d025f4601 to your computer and use it in GitHub Desktop.
Save gangsthub/b2efa76be5314a332cfcfd1d025f4601 to your computer and use it in GitHub Desktop.
`img-exists`

Image Exists

Cheks if a given URL for an image is available over the net. It uses a simple DOM trick to test it. Be careful as <img src> can be an XSS attack vector: https://owasp.org/www-community/xss-filter-evasion-cheatsheet

📦 Install

npm i -S gist:b2efa76be5314a332cfcfd1d025f4601

Usage:

import { imageExists } from 'img-exists'
const src = "https://..."

imageExists(src)
  .then(({ img }) => {
    document.body.appendChild(img) // or whatever
  })
  .catch(({ error }) => console.log(error))
export const imageExists = imageSrc => {
return new Promise((resolve, reject) => {
const img = new Image()
img.onload = () => resolve({ img })
img.onerror = error => reject({ error })
img.src = imageSrc // requests the image
})
}
{
"version": "1.0.1",
"name": "img-exists",
"main": "img-exists.js",
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment