I’m trying to validate URL’s in JavaScript and according to MDN JavaScript’s URL
API is compatible with Chromium browsers and Firefox. However the behaviour varies between the two browsers. Specifically it seems like Chromium browsers are far more lenient and automatically apply encoding and Firefox doesn’t.
I’ve tried encoding the URL myself first before validating with encodeURI('https://abc.co m')
, but Firefox also doesn’t accept https://abc.c%20m
as a valid URL, so I’m stumped as to how I can have a good way to support both browsers without having to resort to regex.
Any ideas for a consistent approach with cross browser support are very welcome. Thanks!
Add function isValidUrl
function isValidURL(url) {
try {
// Attempt to parse the URL using the URL constructor
const parsedURL = new URL(url);
// Check if the domain contains any spaces
if (parsedURL.hostname.includes(' ')) {
return false;
}
// If parsing was successful and there are no spaces in the domain, return true
return true;
} catch (e) {
// If URL parsing fails, return false
return false;
}
}
Domain Space Check: Since browsers may handle spaces differently, manually checking for spaces in the domain part helps ensure consistency across browsers.
Cross-Browser Compatibility: This approach should work consistently across Chromium and Firefox, as it leverages native browser features while accounting for differences.