Sometimes, we want to use JavaScript to detect whether the URL exists before display in iframe.
In this article, we’ll look at how to use JavaScript to detect whether the URL exists before display in iframe.
How to use JavaScript to detect whether the URL exists before display in iframe?
To use JavaScript to detect whether the URL exists before display in iframe, we use fetch
.
For instance, we write
const openHelp = async (urlToOpen) => {
const defaultURL = `http://example.com`;
const response = await fetch(urlToOpen);
if (response.status === 200) {
window.open(urlToOpen, `_blank`);
} else if (response.status === 404) {
window.open(defaultURL, `_blank`);
}
};
to define the openHelp
function.
In it, we check if the urlToOpen
URL is available with fetch
.
We make a get request to it and check if status code.
If it’s 200, then we call window.open
to open the urlToOpen
URL.
If it’s 404, then we call window.open
to open the defaultURL
.
Conclusion
To use JavaScript to detect whether the URL exists before display in iframe, we use fetch
.