Skip to content

Commit

Permalink
feat: test url before opening link
Browse files Browse the repository at this point in the history
  • Loading branch information
Yukaii committed Jul 9, 2023
1 parent a60864e commit 87d602f
Showing 1 changed file with 37 additions and 5 deletions.
42 changes: 37 additions & 5 deletions components/IframePreviewCard/provider.js
Expand Up @@ -68,6 +68,33 @@ const useHoldingShiftKey = () => {
return isHoldingShiftRef
}

// Test if the url is valid and can be iframe embedded
async function headRequest(url) {
try {
const res = await fetch(url, {
method: 'HEAD',
mode: 'no-cors',
})

console.log(res)

return res.ok
} catch (e) {
console.error(e)
return false
}
}

// href might be a relative url or a full url
function parseHref(href) {
try {
const url = new URL(href, window.location.origin)
return url.href
} catch (e) {
return href
}
}

// Note: This is a provider for the IframePreviewCard component
// It should register the clicking event of any external link
// and bring up the IframePreviewCard component
Expand All @@ -80,20 +107,25 @@ export const IframePreviewCardProvider = ({ children }) => {
width > 768
)

const isHoldingAltRef = useHoldingShiftKey()
const isHoldingShiftRef = useHoldingShiftKey()

useMemo(() => {
setPreviewCardEnabled(width > 768)
}, [setPreviewCardEnabled, width])

useEffect(() => {
const handlePreview = (e) => {
const handlePreview = async (e) => {
const { target } = e
const url = target.href
const url = parseHref(target.href)

// test if the url is valid and can be iframe embedded
if (url && !(await headRequest(url))) {
return
}

if (process.env.NODE_ENV === 'production') {
if (
!isHoldingAltRef.current ||
!isHoldingShiftRef.current ||
!previewCardEnabledRef.current ||
isExternalLink(url)
) {
Expand All @@ -109,7 +141,7 @@ export const IframePreviewCardProvider = ({ children }) => {
}
document.addEventListener('click', handlePreview)
return () => document.removeEventListener('click', handlePreview)
}, [isHoldingAltRef, previewCardEnabledRef])
}, [isHoldingShiftRef, previewCardEnabledRef])

return (
<>
Expand Down

0 comments on commit 87d602f

Please sign in to comment.