Im making a website that allows users to view a website of their choosing through iFrames. Heres the script:
<!DOCTYPE html>
<html>
<body>
<div id="container" style="text-align:center;">
<h1>Enter the URL:</h1>
<input type="text" id="urlInput">
<button onclick="showIframe()">Submit</button>
</div>
<script>
function showIframe() {
var url = document.getElementById("urlInput").value;
var iframe = document.createElement("iframe");
iframe.src = url;
iframe.style.position = "absolute";
iframe.style.top = "0";
iframe.style.left = "0";
iframe.style.width = "100%";
iframe.style.height = "100%";
document.body.innerHTML = "";
document.body.appendChild(iframe);
}
</script>
</body>
</html>
The problem is it either wont show the website or the website will “refuse to connect”. Has anybody found a fix to this problem?
I don’t think there is any way to fix it. It is a security feature enabled by the website to prevent malicious activity on it.
2 Likes
Hi there @MorganBarber2! The reason you’re getting this is because the website has a Content Security Policy which basically doesn’t allow anyone to load it in an iframe
. For example, if you try loading the YouTube page in an iframe
, it won’t work.
However, if you use the iframe code that YouTube provides from its videos, like:
<iframe width="999" height="562" src="https://www.youtube.com/embed/dQw4w9WgXcQ" title="Rick Astley - Never Gonna Give You Up (Official Music Video)" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen></iframe>
it will work. Of course, you can modify the tag, however the link must stay the same.
If you don’t own the website, you cannot change this policy, and you unfortunately can’t use it inside an iframe
.
Hope this helps!
This post was flagged by the community and is temporarily hidden.
1 Like