CS Fundamentals Trainer · JavaScript · Security
Predict the output: three ways to decide whether a link is safe to put in href.
Predict the output: three ways to decide whether a link is safe to put in `href`.
const naiveIsSafe = (href) => !href.startsWith('javascript:');
const urlIsSafe = (href) => ['http:', 'https:'].includes(new URL(href, 'https://site.example').protocol);
for (const href of ['/profile', 'JavaScript:alert(1)', ' javascript:alert(1)']) {
console.log(naiveIsSafe(href), urlIsSafe(href), new URL(href, 'https://site.example').protocol);
}
Difficulty: medium