Loading an external URL into a div without using an iframe can be achieved using JavaScript and AJAX. Here’s a basic outline of the steps you can follow:
- Set up an empty div in your HTML where you want to load the external content:
<!DOCTYPE html>
<html>
<head>
<!-- Your head content goes here -->
</head>
<body>
<div id="externalContent"></div>
</body>
</html>
- Use JavaScript to fetch the external content and inject it into the div:
<script>
// Function to load external content into a div
function loadExternalContent(url, targetDivId) {
// Create a new XMLHttpRequest object
var xhr = new XMLHttpRequest();
// Configure the GET request
xhr.open('GET', url, true);
// Set up the event handler when the request is completed
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
// Request was successful, inject the content into the target div
document.getElementById(targetDivId).innerHTML = xhr.responseText;
} else {
// Request failed, handle the error (e.g., show an error message)
document.getElementById(targetDivId).innerHTML = "Failed to load content.";
}
}
};
// Send the request
xhr.send();
}
// Call the function with the URL of the external content and the ID of the target div
var externalURL = 'https://www.example.com/external-page'; // Replace with your desired URL
var targetDivId = 'externalContent'; // Replace with the ID of your target div
loadExternalContent(externalURL, targetDivId);
</script>
In this example, the JavaScript function loadExternalContent
performs an AJAX request to fetch the external URL’s content. Upon successful retrieval, it injects the content into the specified div with the innerHTML
property.
Please note that loading content from external URLs directly into your web page can introduce security risks like Cross-Site Scripting (XSS) attacks if you’re not careful about the source of the content. Make sure you trust the external content source, or implement proper validation and sanitization before displaying it on your page. Additionally, some websites may have cross-origin restrictions that prevent loading their content into other domains using JavaScript due to CORS (Cross-Origin Resource Sharing) policies.