Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update getSiteIcon logic #75

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 16 additions & 14 deletions src/siteMetadata.js
Original file line number Diff line number Diff line change
Expand Up @@ -68,17 +68,11 @@ function getSiteName (window) {
async function getSiteIcon (window) {
const { document } = window

// Use the site's favicon if it exists
let icon = document.querySelector('head > link[rel="shortcut icon"]')
if (icon && await resourceExists(icon.href)) {
return icon.href
}

// Search through available icons in no particular order
icon = Array.from(document.querySelectorAll('head > link[rel="icon"]'))
.find((_icon) => Boolean(_icon.href))
if (icon && await resourceExists(icon.href)) {
return icon.href
const icons = document.querySelectorAll('head > link[rel~="icon"]')
for (const icon of icons) {
if (icon && await resourceExists(icon.href)) {
return true
}
}

return null
Expand All @@ -87,9 +81,17 @@ async function getSiteIcon (window) {
/**
* Returns whether the given resource exists
* @param {string} url the url of the resource
* @return {Promise<boolean>} whether the resource exists
*/
function resourceExists (url) {
return fetch(url, { method: 'HEAD', mode: 'same-origin' })
.then((res) => res.status === 200)
.catch((_) => false)
return new Promise((resolve, reject) => {
try {
const img = document.createElement('img')
img.onload = () => resolve(true)
img.onerror = () => resolve(false)
img.src = url
} catch (e) {
reject(e)
}
})
}