How to identify the document content which is created dynamically inside iframe - javascript

How to identify document content which is created under dynamic iframe
code structure
<div id="test" data-parent-url="/test.html" data-iframe-src="/test-header.html" class="sample-header">
// dynamically created iframe element
<iframe style="border-style: none; width: 100%; height: 105px; display: block;" scrolling="no" id="V1__header" src="/test-header.html">
// dynamically loaded document content
</iframe>
</div>
tried:
var ifrme = document.getElementById('V1__header');
var iframeContent = ifrme.contentWindow.document;
var iframeObj = $(iframeContent);
var contentheight = $(iframeObj.find(selector)[0]).height();
ifrme returns null intermittently, Couldnot find the id. Is there any alternative to find the id and the document content which is creted dynamically in code.

if you cant be sure the iframe is loaded, you could wait by testing at time interval:
var timer = setInterval(function(){
if($('#V1__header').length !=0){
clearIntervall(timer);
Identifydoc();
}
},400);
function idnetifyDoc(){
var ifrme = document.getElementById('V1__header');
var iframeContent = ifrme.contentWindow.document;
var iframeObj = $(iframeContent);
var contentheight = $(iframeObj.find(selector)[0]).height();
}

You can use onload callback:
const ifrme = document.getElementById('V1__header');
ifrme.onload = iframeLoaded;
function iframeLoaded() {
//--> logic
}
Add the script inside the body tag.

Related

How to values from iframe send to div element?

Today I did a my text editor in iframe. I know that values from iframe doesn't send to database. My first idea relies on sending the values from iframe to the div, and that div data send to DataBase with the respective text formats.
function wlaczTrybEdycji(){
edytorTextowy.document.designMode = "On";
}
function execCmd(command){
edytorTextowy.document.execCommand(command, false, null);
}
function przeniesDane(){
var ramka = document.getElementById("ramka");
var dodiv = document.getElementById("daneIframe");
dodiv == ramka;
}
.textarea2{
width: 700px;
float: left;
height: 240px;
border: 2px solid black;
clear: both;
padding: 5px;
}
<body onload="wlaczTrybEdycji();">
<form action="" method="post">
<div class="EdytorTextowy">
<div class="przyciskiTextEdytor">
<button onclick="execCmd('bold');">BOLD</button>
</div>
<iframe name="edytorTextowy" class="textarea2" id="ramka"></iframe>
<div id="daneIframe">
</div>
<button type="submit" name="wyslijText">WYSLIJ</button><!-- here send from "daneIframe" to DB (PHP)-->
</div>
</form>
</body>
One important thing to understand about what you're doing is that the browser has rules about Cross-document communication.
A page inside an iframe is not allowed to access or modify the DOM of its parent and vice-versa unless both have the same origin. So putting it in a different way: document or script loaded from one origin is prevented from getting or setting properties of a document from another origin.
Here's the docs on Same-Origin Policy from MDN.
If the iframe and the page that loads it are of the same origin you should be able to do exactly what you're trying to do just fine. If not, then these documents need to be made available in the same origin to do so.
Hmm I understand now! You can get elements with ajax or javascript like so :
JavaScript for the Example
The JavaScript displayed here is just an example to show how to access to iframe elements.
// attach handlers once iframe is loaded
document.getElementById('ifrm').onload = function() {
// get reference to form to attach button onclick handlers
var form = document.getElementById('demoForm');
// set height of iframe and display value
form.elements.button1.onclick = function() {
var ifrm = document.getElementById('ifrm');
var ht = ifrm.style.height = '160px';
this.form.elements.display.value = 'The iframe\'s height is: ' + ht;
}
// increment and display counter variable contained in iframed document
form.elements['button2'].onclick = function() {
// get reference to iframe window
var win = document.getElementById('ifrm').contentWindow;
var counter = ++win.counter; // increment
this.form.elements['display'].value = 'counter in iframe is: ' + counter;
}
// reference form element in iframed document
form.elements.button3.onclick = function() {
var re = /[^-a-zA-Z!,'?\s]/g; // to filter out unwanted characters
var ifrm = document.getElementById('ifrm');
// reference to document in iframe
var doc = ifrm.contentDocument? ifrm.contentDocument: ifrm.contentWindow.document;
// get reference to greeting text box in iframed document
var fld = doc.forms['iframeDemoForm'].elements['greeting'];
var val = fld.value.replace(re, '');
// display value in text box
this.form.elements.display.value = 'The greeting is: ' + val;
}
form.elements.button4.onclick = function() {
// get reference to iframe window
var win = document.getElementById('ifrm').contentWindow;
win.clearGreeting(); // call function in iframed document
}
}
Or you can do something like this in jquery :
var content=$("iframe").contents().find('body').html();
//alert elements in iframe or show elements as a response in and div
alert(content);

Javascript create iframe set content then return it from one function

I need to create an iframe dynamically, set its html, then return it as a function so it can be called later with newAdUnit(). Right now it returns [object HTMLIFrameElement]. I'm trying to figure out a way to do this all from one function. The reason for this is I'm setting up ads that need to be loaded in dynamically. A single function would make my code a lot cleaner since I can call it in a number of different ways. Any ideas?
<script>
function newAdUnit(size) {
var iframe = document.createElement('iframe');
iframe.onload = function() {
iframe = iframe.contentWindow.document;
var html = '<body>This is a test</body>';
iframe.open();
iframe.write(html);
iframe.close();
};
return iframe;
}
</script>
<div id="test">
<script>document.getElementById("test").innerHTML = newAdUnit()</script>
</div>
It will be so much easy if you use JQuery for the current operation. The code below shows how to
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
function newAdUnit(obj) {
var iframe = document.createElement('iframe');
iframe.onload = function() {
iframe = iframe.contentWindow.document;
var html = '<body>This is a test</body>';
iframe.open();
iframe.write(html);
iframe.close();
};
$(obj).append(iframe);
}
newAdUnit($('#test'));
});
</script>
</head>
<body>
<div id="test">
</div>
</body>
</html>
You should only use .innerHTML when the thing you want to add is a string of HTML. However, in your case, you have a HTMLIFrameElement object, and so, you can't use .innerHTML in this case. Currently, Javascript is implicitly calling .toString() on your element object returned by newAdUnit(), which results in [object HTMLIFrameElement].
Instead, when you want to add a node element to another element, you can use .appendChild() like so:
<div id="test"></div>
<script>
function newAdUnit(size) {
var iframe = document.createElement('iframe');
iframe.onload = function() {
iframe = iframe.contentWindow.document;
var html = '<body>This is a test. The size is ' + size + '</body>';
iframe.open();
iframe.write(html);
iframe.close();
};
return iframe;
}
document.getElementById("test").appendChild(newAdUnit(10));
</script>

javascript: IFrame-SRC as new Window?

I have a web application in which I have a bunch of iFrame from with source from other tools.
Now the user should have the possibility to open the iframe content in a new window / new tab, normaly I would simply add something like this:
function onButtonClick() { var src = $('#iframe').prop('src');
windows.open(src, "_blank"); }
But his would only open a new version of my iFrame context, e.g. if a user open a page in the iframe or clicked on something and javascript changed something within my iframe, the user would be loosing this value..
So, can I make a iframe Content to a new window content without loosing the dynamic state of the website within my iframe?
You cannot move around iframes between different windows without reloading, because the spec says the attributes must be reevaluated:
When an iframe element is inserted into a document that has a browsing context, the user agent must create a nested browsing context, and then process the iframe attributes for the "first time".
-- https://html.spec.whatwg.org/multipage/embedded-content.html#the-iframe-element
(via https://bugzilla.mozilla.org/show_bug.cgi?id=254144#c97)
Old answer:
// edit: Does not work as expected, since the iframe is reloaded on move and the original src is restored.
It is easy enough if you move the iframe out of the current page:
<button id="example-button">open in new window</button>
<div id="example-container">
<iframe id="example-iframe" src="https://example.com/">
</iframe>
</div>
document.getElementById('example-button').addEventListener('click', function (ev) {
ev.preventDefault();
var win = open('about:blank');
var iframe = document.getElementById('example-iframe');
// the popup might not be immediately available:
setTimeout(function () {
var body = win.document.body;
body.style.padding = 0;
body.style.margin = 0;
body.appendChild(iframe);
iframe.style.position = 'fixed';
iframe.style.padding = 0;
iframe.style.margin = 0;
iframe.style.width = '100%';
iframe.style.height = '100%';
iframe.style.border = 0;
}, 0);
// move the iframe back if the popup in closed
win.addEventListener('beforeunload', function () {
document.getElementById('example-container').appendChild(iframe);
iframe.style.position = '';
iframe.style.padding = '';
iframe.style.margin = '';
iframe.style.width = '';
iframe.style.height = '';
iframe.style.border = '';
});
});
Example: http://jsfiddle.net/cpy2jykv/1/

Detect scrollbars within iFrame JS

My webpage has an embedded iFrame which is using a 3rd party tool within my webpage which means the URL from the iFrame is coming from a different location.
I need to detect the presentation of a scroll bar within the iFrame window when resizing the page, then carrying out a task once it has been detected.
I have tried a variety of different solutions all which have not been successful.
Is this possible?
Many Thanks!
This is the first thing that comes to my mind: http://jsfiddle.net/matias/hhcKn/
just sample code!
HTML:
<div id="body"></div>
JS:
var $iframe = $("<iframe></iframe>").appendTo("#body");
var iframe = $iframe[0];
var doc = iframe.document;
//test this
var content = "<h1>Hello world</h1><br><p>more content!</p>";
//and then this
//var content = "<h1>Hello world</h1><br><br><br><br><br><p>more content!</p>";
if(iframe.contentDocument){
doc = iframe.contentDocument;
}
else if(iframe.contentWindow){
doc = iframe.contentWindow.document;
}
doc.open();
doc.writeln(content);
doc.close();
//this is the part that might interest you
var div_height = $("#body").height();
var iframe_height = $("iframe").contents().height();
if(iframe_height > div_height) alert("scrollbars present");
CSS:
body{
border: 1px solid red;
}
iframe{
border: none;
}
<iframe src="111.html" id="iframeid" height="300" width="800"></iframe>
<script type="text/javascript">
function resizeIFrame(){
$("#iframeid").attr("height", $("#iframeid").contents().height());
}
setInterval("resizeIFrame()", 500)
</script>

How to add event to the body of a dynamically created iframe in jQuery?

I've tried:
$(document).on("event", window.iframe_name.doument.getElementsByTagName["body"][0], function(){
//code
});
but it doesn't seem to work.
First you have to wait for the iFrame to load.
$(function(){
$('#iFrame').load(function(){
//then set up some access points
var frame = document.getElementById('iFrame'); // referance to the iframe
var frameWindow = frame.contentWindow; // referance the iframes window
var contents = $(this).contents(); // contents of the iframe
frameWindow.$('body').on(//your code here)
})
})

Categories