How to get innerHTML content of iframe element - javascript

hi i am trying to get inner HTML of iframe element
my html document a structure is like this
<body>
<div>
<iframe id="frame1">
<html>
<button id="mybutton">click me</button>
</html>
</iframe>
</div>
</body>
i am creating a chrome extension i have to show an alert when button with id mybutton is clicked i write an a content script
var greeting = "hola, ";
document.body.innerHTML='<div><iframe id="frame1" src="http://onemoredemo.appspot.com/"></iframe></div>' ;
var iframe = document.getElementById("frame1");
var iframeDocument = iframe.contentDocument || iframe.contentWindow.document
var button = iframeDocument.getElementById("mybutton") ;
if(button ==null)
alert("button is null") ;
i installed this extension in chrome when i visit a page then document body is changed into an iframe with a button in it.
but i am facing an alert which has button is null but there is button in iframe why i am getting null for this button??

To get the button inside of the iframe, this could work:
var iframe = document.getElementById("frame1");
var iframeDocument = iframe.contentDocument || iframe.contentWindow.document;
var button = iframeDocument.getElementById("mybutton");
Obviously, you can navigate to get what you want with iframeDocument, and use .innerHTML as you seem to know. You cannot get the contents of the iframe if the iframe is pointing to a domain other than its parent.
UPDATE:
You need to use the code to get the frame's document and its contents after it's ready, so you should use something like this:
window.onload = function () {
var greeting = "hola, ";
var div1 = document.createElement("div");
var frame1 = document.createElement("iframe");
frame1.id = "frame1";
frame1.onload = function () {
alert("loaded");
var iframe = document.getElementById("frame1");
var iframeDocument = iframe.contentDocument || iframe.contentWindow.document;
var button = iframeDocument.getElementById("mybutton");
if (button == null) {
alert("button is null");
}
};
frame1.src = "http://onemoredemo.appspot.com";
div1.appendChild(frame1);
document.body.appendChild(div1);
};
DEMO: http://jsfiddle.net/nqTnz/
The important thing is how the elements are created and appended to the DOM - not just using innerHTML. The onload method of the iframe is to guarantee it's ready. The actual manipulation code won't work in the jsFiddle because the cross-domain problems, but is what you should need.

In jQuery's source code the solution to get the iframe document is like this:
var iframeDocument = iframe.contentDocument || iframe.contentWindow.document;
And then you can usually use getElementsByTagName or getElementById to select the DOM-Elements:
var elem;
if (iframeDocument) {
elem = iframeDocument.getElementById('mybutton');
}

Have You tried ????
iframe.srcdoc="<HTML><a id='some_id'>old</a><script>function run(src){eval(src);}</script></HTML>";
And then
iframe.contentWindow.run("document.getElementById('some_id').innerHTML='new content';");

Related

How to get id of element in an iframe?

I have an <iframe> with a local file embedded. I don't know how to get a specific element in this document.
I have tried window.top.document.getElementById('numPages') and $("#myiframe").contents().find("#numPages") to get element with an id of numPages.
Try using .contentDocument
eg:
var iframe = document.getElementById("myFrame"),
idocument = iframe.contentDocument
// Use idocument instead of document
To get the element in plain javascript try using contentWindow
document.getElementById('myiframe').contentWindow.document.body.getElementById('numPages');
By this way, You can get frame id and set css property inside frame element. It'll work 100%.
<script>
window.onload = function WindowLoad(event) {
let iframe = document.getElementsByTagName("iframe")[0];
var iframevar = document.getElementById(iframe.id);
var elmnt = iframevar.contentWindow.document.getElementById("header_27");
elmnt.style.color = 'black';
var elmnt = iframevar.contentWindow.document.getElementById("header_59");
elmnt.style.color = 'black';
}
</script>

Iframe element not auto delete the content

Any idea why at this jsfiddle the iframe is auto deleting its content? How can i overcome this error?
HTML
<iframe id = "Preview"></iframe>
JS
document.ready = (function(){
document.getElementById('Preview').src = "about:blank";
var iframe = document.getElementById('Preview'),
iframedoc = iframe.contentDocument || iframe.contentWindow.document;
iframedoc.body.innerHTML = "<html>To preview the xml/gml file visit<a href = 'about:blank' target = '_blank'></a></html>";
alert()
})();
It is because you are setting the src of the iframe.
You just have to get rid of :
document.getElementById(' Preview ').src = " about:blank ";

get all content of div including content of iframes using javascripts not jquery

I Have a div something like this
<div id="tid">
<iframe>
<html>
<body>
<scripts></scripts>
<iframe>...
//more content
<ifram>
</body>
</html>
</iframe>
</div>
I want to get below using javascript.
<iframe>
<html>
<body>
<scripts></scripts>
<iframe>...
//more content and cannot guess how many iframes are there.
<ifram>
</body>
</html>
</iframe>
InnerHtml only return first iframe only. I tried with .contentDocument.getElementsByTagName('body')[0].innerHTML. but this only return first iframe. I want get all the content into string variable without using jquery.
Thanks
YOU NEED TO REPLACE < WITH < AND > WITH > TO PRINT HTML TAGS AS A PLAIN TEXT.
try this code,
var content = document.getElementById('tid').innerHTML;
content = content.replace(/</g,"<").replace(/>/g,">");
document.getElementById('content').innerHTML = content;
SEE THIS DEMO
if you want to reuse that div html, simply add that content to any other html element like below,
var content = document.getElementById('tid').innerHTML;
//the variable content contains the html inside "tid" div.
var iDiv = document.createElement('div');
iDiv.id = 'newDiv';
iDiv.innerHTML = content;
document.getElementsByTagName('body')[0].appendChild(iDiv);
SEE THIS DEMO
If you only want the body tags this should work.
var els = document.getElementsByTagName("body");
var allContent = "";
for (var i=0; i < els.length; i++) {
allContent += els[i].innerHTML;
}
Do this
var iframe = document.getElementById('iframeID');
var iframeDocument = iframe.contentDocument || iframe.contentWindow.document;
now you can use iframeDocument to access content of iframe, jquery does the same
UPDATE
You can do something like this ..
var myDiv = document.getElementById("tid");
var iframes = myDiv.getElementsByTagName("iframe");
// now loop over the iframes
for(iframe in iframes){
var iframeDocument = iframe.contentDocument || iframe.contentWindow.document;
var internalIframes = iframeDocument.getElementsByTagName("iframe");
if(internalIframes.length > 1){
// start the for in loop again
}
}
can not do this because of same origin policy

Inserting text into an editable IFRAME at the caret position (IE)

I'm struggling with an actually straighforward problem: In Internet Explorer I want to insert plain text at the current caret position. This works really fine for simple TEXTAREA elements but it doesn't entirely work for editable IFRAMEs, which is what I have.
In the script I use I am creating a TextRange object from the document of the IFRAME which I use to paste the text as HTML at the cursor position.
<iframe id="editable">
<html>
<body>
Some really boring text.
</body>
</html>
</iframe>
<script type="text/javascript">
window.onload = function() {
var iframe = document.getElementById('editable');
var doc = iframe.contentDocument || iframe.contentWindow.document;
doc.body.innerHTML = iframe.textContent || iframe.innerHTML;
// Make IFRAME editable
if (doc.body.contentEditable) {
doc.body.contentEditable = true;
}
}
function insert(text) {
var iframe = document.getElementById('editable');
var doc = iframe.contentDocument || iframe.contentWindow.document;
iframe.focus();
if(typeof doc.selection != 'undefined') {
var range = doc.selection.createRange();
range.pasteHTML(text);
}
}
</script>
<input type="button" value="Insert" onClick="insert('foo');"/>
When I select some text in the IFRAME, the selection will be replaced with "foo" - this is expected behaviour. But when I just place the caret somewhere in the text, the insertion won't work.
Is this common behaviour, as there is "no real selection" for the case that I just place the cursor somewhere or is it a bug with editable IFRAMEs in IE, since it works pretty well with simple TEXTAREA elements?
Is there a workaround?
You may find it works if you use onmousedown rather than onclick in your button.
UPDATE
The reason why this makes a difference is that the click event fires after the iframe has lost focus (which destroys a collapsed selection in IE) whereas mousedown fires before.
FURTHER UPDATE
You could also try fixing this in IE by saving/restoring the selected TextRange as the iframe loses/receives focus. Something like this should work:
function fixIframeCaret(iframe) {
if (iframe.attachEvent) {
var selectedRange = null;
iframe.attachEvent("onbeforedeactivate", function() {
var sel = iframe.contentWindow.document.selection;
if (sel.type != "None") {
selectedRange = sel.createRange();
}
});
iframe.contentWindow.attachEvent("onfocus", function() {
if (selectedRange) {
selectedRange.select();
}
});
}
}
window.onload = function() {
var iframe = document.getElementById('editable');
fixIframeCaret(iframe);
};

how to get selected text from iframe with javascript?

how to get selected text from iframe with javascript ?
var $ifx = $('<iframe src="filename.html" height=200 width=200></iframe>').appendTo(document.body);
$(document.body).bind('click', function(){
var u_sel;
if(window.getSelection){
u_sel = ifx[0].contentWindow.getSelection();
// u_sel.text() InternetExplorer !!
alert(u_sel);
}
});
That should do it, as long as the iframe src is targeting your own domain.
Tested only on FireFox 3.6.7 so far.
function getIframeSelectionText(iframe) {
var win = iframe.contentWindow;
var doc = iframe.contentDocument || win.document;
if (win.getSelection) {
return win.getSelection().toString();
} else if (doc.selection && doc.selection.createRange) {
return doc.selection.createRange().text;
}
}
var iframe = document.getElementById("your_iframe");
alert(getIframeSelectionText(iframe));
As noted by jAndy, this will only work if the iframe document is served from the same domain as the containing document.

Categories

Resources