how to get selected text from iframe with javascript? - 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.

Related

Verify iFrame content and update containing DIV Height

I have a block of JQuery that was already provided by the previous developer but I am not 100% sure I understand what it is doing. I thought it had to do with setting the height of an iFrame based on its contents.
var iframeId = "iframeFinancial";
var origin = "http://content.net";
//I am not 100% sure what is going on over the next 3 lines
var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
var eventListener = window[eventMethod];
var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";
eventListener(messageEvent,function(e) {
var message = e.data;
if(e.origin !== origin) return; // change to vanity url if applicable
updateIFrame(message);
},false);
function updateIFrame(msg) {
console.log('In Update Iframe Function');
if(typeof msg != 'object') {
var iframe = document.getElementById(iframeId); // iframe id
iframe.setAttribute('height',msg);
} else { // for multiple iframe support
var id = msg.id;
var height = msg.height;
var object = document.getElementById(id);
object.setAttribute('height',height);
}
}
But when the iFrame loads I never make it into the updateIFrame function based on what I am seeing in the console.
I also tried the following on my own but got this error:Error: Permission denied to access property "document"
document.getElementById("iframeFinancial").onload = function()
{
var iFrameID = document.getElementById('iframeFinancial');
iFrameID.height = "";
iFrameID.height = iFrameID.contentWindow.document.body.scrollHeight + "px";
console.log('In new function');
}
I checked the page being loaded into the iFrame and found the following snippet of JS at the bottom of the page:
(function ($) {
var wrapper = document.getElementById('wrapper'); // the container element of the phx content.
var height = Math.max( wrapper.offsetHeight, wrapper.scrollHeight );
parent.postMessage(height,"*");
}(Phx.$));
Based on what is shown here do I need to update the JQUERY mentioned at the top of the question.

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 ";

javascript function convert into jquery equivalent

I have a javascript function written as follows which works just fine in Firefox for downloading given txt content.
self.downloadURL = function (url) {
var iframe;
iframe = document.getElementById("hiddenDownloader");
if (iframe === null) {
iframe = document.createElement('iframe');
iframe.id = "hiddenDownloader";
iframe.style.display = "none";
document.body.appendChild(iframe);
}
iframe.src = url;
}
but it does n't work fine with IE 9 due to some reasons. So i tried to convert into equivalent jquery because jquery has compatibility with all the browsers.
here is the jquery equivalent of the same function:
self.downloadURL = function (url) {
var iframe;
iframe = $("#hiddenDownloader");
if (iframe === null) {
iframe = $('<iframe></iframe>');
iframe.id = "hiddenDownloader";
$("#hiddenDownloader").css("display", "none");
$(document.body).append(iframe);
}
iframe.src = url;
}
But now it does n't work in both the browsers. Please help letting me know what am i doing wrong.
Your problem is in:
iframe = $('<iframe></iframe>');
iframe.id = "hiddenDownloader";
iframe refers to a jQuery Object not a DOM Node. You will have to use .prop to set the id:
iframe = $('<iframe></iframe>');
iframe.prop('id', "hiddenDownloader");
And also you have the same problem here:
if (iframe === null) {
Where you will need the check the length of iframe:
if (iframe.length === 0) {
And again at iframe.src = url; Maybe you can figure this one out:
iframe.attr('src', url);
But why would you convert vanilla JavaScript to jQuery?
Seems like a strange way to download a file.
In any case, this probably works the same was as the original:
if (!iframe.get(0)) {
...
}
... and the id property as another poster mentions.
iframe = document.getElementById("hiddenDownloader");
iframe = $("#hiddenDownloader");
These lines aren't equivalent. The second one create a jQuery object, so the check for null will never equate to true
This link may help u:
http://www.sitepoint.com/forums/showthread.php?743000-IE9-Iframes-DOCTYPES-and-You
or u can add this to the top:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
Replace iframe.src = url; with iframe.attr("src",url + "?"+ Math.random()); to prevent caching issue in IE9.
Replace iframe.id = "hiddenDownloader"; with iframe.attr("id","hiddenDownloader");
Replace if (iframe === null) { with if (iframe.length === 0) {
Try with:
iframe = $("#hiddenDownloader")[0];

How to get innerHTML content of iframe element

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';");

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);
};

Categories

Resources