Creating an iframe with given HTML dynamically
Setting the src
of a newly created iframe
in javascript does not trigger the HTML parser until the element is inserted into the document. The HTML is then updated and the HTML parser will be invoked and process the attribute as expected.
http://jsfiddle.net/9k9Pe/2/
var iframe = document.createElement('iframe');
var html = '<body>Foo</body>';
iframe.src = 'data:text/html;charset=utf-8,' + encodeURI(html);
document.body.appendChild(iframe);
console.log('iframe.contentWindow =', iframe.contentWindow);
Also this answer your question it's important to note that this approach has compatibility issues with some browsers, please see the answer of @mschr for a cross-browser solution.
How to add an iframe element into html dynamically?
When you change your select option you can listen to onchange
event and do your logic there.
The code should look somehting like this:
var $sel = document.getElementById('explanationType');
$sel.onchange = function (e) { var selectedValue = e.target.value; var $option = e.target.options[e.target.selectedIndex]; var url = $option.getAttribute('kibanaurl');
if (url) { document.getElementById("js-iframe").setAttribute('src', url); }
if (selectedValue === 'SHAP') { var $newIFrame = document.createElement("iframe"); $newIFrame.setAttribute("src", "http://example.com"); $newIFrame.style.width = "300px"; $newIFrame.style.height = "300px"; document.body.appendChild($newIFrame); }}
<!DOCTYPE html><html><head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>Test</title></head><body> <select id="explanationType"> <option value="SHAP" kibanaurl="https://image.shutterstock.com/image-vector/example-sign-paper-origami-speech-260nw-1164503347.jpg">SHAP</option> <option value="LIME" kibanaurl="https://upload.wikimedia.org/wikipedia/commons/8/84/Example.svg">LIME</option> </select>
<iframe id="js-iframe" src="https://www.youtube.com/watch?v=hVCYwwFwGEE&list=RDhVCYwwFwGEE&index=1" width="100%" height="80%" frameborder="0"> <p>Your browser does not support iframes.</p> </iframe> </body></html>
Dynamic iframe content from js response
Here's a quick modification of your code to show how its possible.
Your doc variable is the document element of the iFrame. Setting a variable on it will allow you to access it from code running within the iFrame.
https://jsfiddle.net/78gf5e8q/
(function(d) {
var iframe = d.body.appendChild(d.createElement('iframe')),
doc = iframe.contentWindow.document,
options = {
objid: 152,
key: 316541321
},
//src = "host/widget.js",
uri = encodeURIComponent(JSON.stringify(options));
doc.someVar = "Hello World!";
iframe.id = "iframewidget";
iframe.width = 200;
iframe.height = 300;
var html = '<body onload="var d=document;' +
'd.getElementsByTagName(\'head\')[0].appendChild(d.createElement(\'script\')).innerHTML=\'alert(document.someVar)\'">';
doc.open().write(html);
doc.close();
})(document);
Edit: you were also passing in a non existent var called js into doc.open().write(js); I changed it to .write(html);
Edit 2: For cross domain you'll probably get "Permission Denied" on that var.
Listen click text in dynamically created iframe
I have tested both @Teemu and @Tanay answer . It works when I added in document.addEventListener('load',function(event){//sucessfully fired when added here})
Then, I have change iframe.src to source document, page1.html
.
<html>
<head>
<script src="../ext/plugins/jquery/dist/jquery.min.js"></script>
<script>
$(document).ready(function(){
//add iframe
var iframe = document.createElement('iframe');
var html = '<body>Foo</body>';
//iframe.src = 'data:text/html;charset=utf-8,' + encodeURI(html);
iframe.src = 'page1.html';
$('#iframe-holder').append(iframe);
})
document.addEventListener(
'load',
function(event){
//1:
$($('#iframe-holder > iframe')[0].contentDocument).on('click', function (e) {
console.log('ln34');
});
//2:
const iframe = document.querySelector('#iframe-holder > iframe');
iframe.onload = function() {
const iframeDocument = iframe.contentWindow.document;
iframeDocument.addEventListener('click', function(e) {
console.log('ln43');
})
}
},
true // Capture event
);
</script>
</head>
<body>
<div id="iframe-holder">
</div>
</body>
Thank you for help.
Create a dynamic iframe that receive its URL from the address bar
You can use the split method on the string of the url and take everything after the '?' by targetting the [1] position of the resulting array, then change the iframe's 'src' attribute to that url.
var url = window.location.href.split('?')[1];
document.querySelector('iframe').setAttribute('src',url);
Try breaking the first line into two like this:
var url = window.location.href;
url.split('?')[1];
document.querySelector('iframe').setAttribute('src',url);
Creating an IFRAME using JavaScript
You can use:
<script type="text/javascript">
function prepareFrame() {
var ifrm = document.createElement("iframe");
ifrm.setAttribute("src", "http://google.com/");
ifrm.style.width = "640px";
ifrm.style.height = "480px";
document.body.appendChild(ifrm);
}
</script>
also check basics of the iFrame element
dynamically set iframe src
<script type="text/javascript">
function iframeDidLoad() {
alert('Done');
}
function newSite() {
var sites = ['http://getprismatic.com',
'http://gizmodo.com/',
'http://lifehacker.com/']
document.getElementById('myIframe').src = sites[Math.floor(Math.random() * sites.length)];
}
</script>
<input type="button" value="Change site" onClick="newSite()" />
<iframe id="myIframe" src="http://getprismatic.com/" onLoad="iframeDidLoad();"></iframe>
Example at http://jsfiddle.net/MALuP/
Filling an IFRAME with dynamic content from JavaScript
I think you're looking for something like:
var iframeDoc = myIframe.contentWindow.document;
iframeDoc.open();
iframeDoc.write('hello world');
iframeDoc.close();
Related Topics
Detecting Back Button/Hash Change in Url
How to Define Custom Sort Function in JavaScript
Difference Between Window.Location.Href=Window.Location.Href and Window.Location.Reload()
Shrink Div to Text That's Wrapped to Its Max-Width
How to Bind the HTML <Title> Content in Vuejs
Session Only Cookies with JavaScript
Counting and Limiting Words in a Textarea
Javascript: Get Image Dimensions
Possible to Associate Label with Checkbox Without Using "For=Id"
How to Get the Index of an Object by Its Property in JavaScript
Highlight Text Range Using JavaScript
How to Remove One Specific Selected File from Input File Control
Adding a New Array Element to a JSON Object
Why Is the Variable Holding the Input Value Always Logged as Empty
Webpack File-Loader Outputs [Object Module]