In case we want to render Html dynamically into website as frame without hosting the Html into another website, we can use of this code Blob with createObjectURL to render dynamically,
Create Parent Website as below:
<html>
<head>
<script>
// This function will update the iframe src
with the HTML code from the textarea
function renderHTML() {
var textarea =
document.getElementById("html-code");
// Get the iframe
element by its id
var
iframe = document.getElementById("html-frame");
//
Create a blob object from the textarea value
var
blob = new Blob([textarea.value], {type: "text/html"});
//
Create a URL object from the blob object
var
url = URL.createObjectURL(blob);
//
Set the iframe src to the URL object
iframe.src = url;
}
function postIframe(){
var
iframe = document.getElementById("html-frame");
iframe.contentWindow.postMessage("Hi,
Message From Parent Website", '*');
}
</script>
</head>
<body>
<h1>HTML Editor</h1>
<p>Enter some HTML code in the textarea below and click the button to render
it in the iframe.</p>
<textarea id="html-code" rows="10" cols="50">
<h2>Hello World</h2>
<p>This is a simple HTML document.</p>
</textarea>
<br>
<button onclick="renderHTML()">Render HTML</button>
<br>
<iframe id="html-frame" width="500" height="300"></iframe>
<br />
<button onclick="postIframe()">Post Iframe</button>
</body>
</html>
In case we want to communicate with iFrame, we can use of postMessage, for that we can add the following code into Html of iFrame
iFrame Html Content as below:
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<h1>This is a Heading</h1>
<p>This is a paragraph.</p>
<script type="text/javaScript">
function addListener() {
window.addEventListener('message', event => {
// IMPORTANT: check the origin of the data!
//if (event.origin === 'https://your-parent-site-url') {
// The data was sent from your site.
// Data sent with postMessage is stored in event.data:
alert(event.data);
//} else {
// The data was NOT sent from your site!
// Be careful! Do not use it. This else branch is
// here just for clarity, you usually shouldn't need it.
return;
//}
});
}
addListener();
</script>
<div> Footer Content</div>
</body>
</html>
No comments:
Post a Comment