Javascript writing in iframe

How to insert javascript code in iframe tag

I am doing like this but not working:- I am trying to insert the pixel in iframe and then append it to the body.

jQuery('#subscribr').append(' '); enter code here 

3 Answers 3

Scripts like that appear to break when is included in the string. A workaround to that could be to add the elements through dom manipulation:

iframe = $(''); var script = document.createElement("script"); script.type = "text/javascript"; script.src = "http://www.abc/static/st.v2.js"; // Or: script.text = "Your code here!" iframe[0].appendChild(script); iframe.appendTo('#subscribr')) 

This is the solution which worked for me..

var s = document.createElement("script"); s.type = "text/javascript"; s.src = "http://www.abc/static/st.v2.js"; // Use selector here jQuery("#subscribr").append(s); 
var doc = null; if(iframe.contentDocument) doc = iframe.contentDocument; else if(iframe.contentWindow) doc = iframe.contentWindow.document; else if(iframe.document) doc = iframe.document; if(doc == null) throw "Document not initialized"; doc.open(); var script = doc.createElement("script"); script.type = "text/javascript"; // script.src = 'http://www.abc/static/st.v2.js'; script.text = "alert('voila!');" doc.appendChild(script); doc.close(); 

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.7.17.43537

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

Write elements into a child iframe using Javascript or jQuery

And I would like to use jQuery to write elements such that the full equivalent HTML would be like this:

Читайте также:  Язык программирования пайтон или питон

Alternatively, any plain-old-Javascript would be fine. Thanks. Edit: After a little more research, it seems I am looking for an IE-equivalent of the contentDocument property of an iframe. «contentDocument» is a W3C standard which FF supports, but IE does not. (surprise surprise)

5 Answers 5

You can do both, you just have to target differently:

var ifrm = document.getElementById('myIframe'); ifrm = ifrm.contentWindow || ifrm.contentDocument.document || ifrm.contentDocument; ifrm.document.open(); ifrm.document.write('Hello World!'); ifrm.document.close(); 

this method no longer works. I get js error that says Unsafe JavaScript attempt to access frame with URL «URL1» from frame with URL «URL2». Domains, protocols and ports must match. The bridge approach given bellow does work fine.

I know this an old thread but in what case would you ever have ifrm.contentDocument.document.document ?

without close() statement all following JS are not executed, so it make sense to use try finally block. thanks. this answer helped me to figure out what is wrong with my page

After some research, and a corroborating answer from Mike, I’ve found this is a solution:

 var d = $("#someFrame")[0].contentWindow.document; // contentWindow works in IE7 and FF d.open(); d.close(); // must open and close document object to start using it! // now start doing normal jQuery: $("body", d).append("
A
B
C
");

HTMLIFrameElement: srcdoc property

The srcdoc property of the HTMLIFrameElement specifies the content of the page.

document.querySelector("button").addEventListener("click", function() < document.querySelector("iframe").srcdoc = "Hello, world!"; >);

I am going out on a limb here and suggest that the answers proposed so far are not possible.

If this iframe actually has a src=»https://stackoverflow.com/questions/997986/somepage.html» (which you ought to have indicated, and if not, what is the point of using iframe?), then I do not think Jquery can directly manipulate html across frames in all browsers. Based on my experience with this kind of thing, the containing page cannot directly call functions from or make any sort of Javascript contact with the iframe page.

Your «somepage.html» (the page that loads in the iframe) needs to do two things:

  1. Pass some kind of object to the containing page that can be used as a bridge
  2. Have a function to set the HTML as you desired

So for example, somepage.html might look like this:

and the containing page might look like this:

This may appear a bit convoluted but it can be adapted in a number of directions and should work in at least IE, FF, Chrome, and probably Safari and Opera.

Thanks for your answer — but I want to use this iframe to compose HTML like a rich text editor. I don’t set the src attribute since it will be cleared out and re-composed from the «top» window. Also — I think it must be possible to reach into the child’s DOM — see my edit in the OP.

Is there any reason you need to use an iframe and not a div? seems like the div would be easier and less likely to break across browsers.

Turns out, there is a reason. You need to place external javascript and don’t want it to damage your page. But you also need the referer to match your top-level domain. This is the most common method of placing ads on a page: + document.write(»)

I have found this to be cross-browser compatible. a little crossing of previous answers and a bit of trial & error of my own. 🙂

I’m using this for a download of a report, or, if an error (message) occurs, it’s displayed in the iFrame. Most of the users will probably have the iFrame hidden, I’m using it multi-functional.

The thing is I have to clear the contents of the iFrame every time I click the report download button — the user can change parameters and it happens there are no results which then is displayed in the iFrame as a message. If there are results, the iFrame remains empty — because the code below has cleared it and the window.open(. ) method generates a Content-Disposition: attachment;filename=. document.

var $frm = $("#reportIFrame"); var $doc = $frm[0].contentWindow ? $frm[0].contentWindow.document : $frm[0].contentDocument; var $body = $($doc.body); $body.html(''); // clear iFrame contents Writing into the iFrame. '); // use this to write something into the iFrame window.open(Module.PATH + 'php/getReport.php' + Report.queryData, 'reportIFrame'); 

I do not have a browser that supports contentDocument but I’ve coded it this way so I’m leaving it. Maybe someone has older browsers and can post compatibility confirmation/issues?

Источник

Insert content into iFrame

If you absolutely have to use jQuery, you should use contents() :

var $iframe = $('#iframe'); $iframe.ready(function() < $iframe.contents().find("body").append('Test'); >); 

Please don’t forget that if you’re using jQuery, you’ll need to hook into the DOMReady function as follows:

I agree that jQuery is a bit overkill for some simple DOM manipulation but I’ve already got it for other parts of the page anyway, but thanks for the detailed response

No problem, glad to help. Please bear in mind though that using jQuery is not always best option. In this example, it will be slower, of course.

Anyone faced any cross-domain security validations thrown by IE ? I am seeing those with this example. Any idea on how to work arounds ?

Changed to var ifr = d.getElementById(‘iframe’), doc = ifr.contentDocument || ifr.contentWindow.document; . Got it from thinkofdev.com/…

This is not a bad solution because many browsers give you a warning when you use doc.write(); it is highly discouraged.

This should do what you want:

Check this JSFiddle for working demo.

Edit: You can of course do it one line style:

$("#iframe").contents().find("body").append('Test'); 

Just because he’s named variables with $ doesn’t mean it’s a weird combination of PHP and JS. I actually sometimes name variables that hold jQuery objects as $testDiv , for example. It helps me track jQuery objects inside my code. The prepended $ on variable names has nothing to do with JS syntax.

If you’re using the jquery function find does that mean the iframe already has a body tag in it — or am I missing somehting?

@user2521439 yes. iframes are created with a blank document inside. The browser will automatically add to your iframe’s contentDocument.

Wait, are you really needing to render it using javascript?

Be aware that in HTML5 there is srcdoc , which can do that for you! (The drawback is that IE/EDGE does not support it yet https://caniuse.com/#feat=iframe-srcdoc)

Another thing to note is that if you want to avoid the interference of the js code inside and outside you should consider using the sandbox mode.

You can enter (for example) text from div into iFrame:

var $iframe = $('#iframe'); $iframe.ready(function() < $iframe.contents().find("body").append($('#mytext')); >); 

It would be better to have text in English (even though in this case understanding it is not very important). Also, as a general tip, a few words to explain how your solution works would be welcome. It would save people from analysing the code to understand whether your solution is what they are looking for. Thank you!

If you want all the CSS thats on your webpage in your IFrame , try this:

var headClone, iFrameHead; // Create a clone of the web-page head headClone = $('head').clone(); // Find the head of the the iFrame we are looking for iFrameHead = $('#iframe').contents().find('head'); // Replace 'iFrameHead with your Web page 'head' iFrameHead.replaceWith(headClone); // You should now have all the Web page CSS in the Iframe 

Источник

how can i load ‘s into an iframe?

Maybe the error is with your string, never create a string in javascript with a literal < /script> in it.

Gah! How could I miss that?! I even pointed it out to someone else in another question (not on SO) earlier today. Wish I could +2 this.

«. never create a string with. « Well, creating it (as you have done) is fine. It’s having the literal one there that’s the problem.

i was nearly there in the question «The problem is something to do with the inserted script tags not being escaped properly» haha, thanks guys

I’m a bit surprised that isn’t working [Edit: No longer surprised at all, see mtrovo’s answer.]. but here’s what I do, which is mostly non-jQuery per your comment below but still quite brief:

var rawframe = document.getElementById('theframe'); var framedoc = rawframe.contentDocument; if (!framedoc && rawframe.contentWindow) < framedoc = rawframe.contentWindow.document; >var script = doc.createElement('script'); script.type = "text/javascript"; script.src = "http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"; framedoc.body.appendChild(script); 

Off-topic: I really wouldn’t give an iframe (or anything else) the ID «iframe». That just feels like it’s asking for trouble (IE has namespace issues, and while I’m not aware of it confusing tag names and IDs, I wouldn’t be completely shocked). I’ve used «theframe» above instead.

Источник

Оцените статью