IE caches dynamically added iframe. Why, and how do I prevent it? - javascript

I have the following HTML / JS:
<html>
<body>
<script>
function foo(){
var html = "<iframe src=\"foo.html\" />";
document.getElementById('content').innerHTML=html;
}
function bar(){
var html = "<iframe src=\"bar.html\" />";
document.getElementById('content').innerHTML=html;
}
function show(){
alert(document.getElementById('content').innerHTML);
}
</script>
<button onclick="foo()">foo</button><br />
<button onclick="bar()">bar</button><br />
<button onclick="show()">test</button><br />
<div id="content"></div>
</body>
</html>
This sort of works as expected, even in IE. Until I hit F5. When I first click foo, I get an iframe with the contents of foo.html, as expected. I then refresh, and hit bar. Instead of getting the contents of bar.html, I see the contents of foo.html. Strangely, when I click test, the alert() tells me the src attribute for the iframe is correctly set to bar.html. Firefox has no such issue.
Why does this happen, and how do I prevent it?
edit: what I forgot to mention is that I can't put the iframe in and change the src attribute. In the real situation I have, sometimes I need an <img> rather than an <iframe>.

Use this DOM
<div id="content" style='display:none;'>
<iframe id='contentFrame' src='' />
</div>
And this as your script
function foo() {
var contentDiv = document.getElementById('content');
var contentFrame = document.getElementById('contentFrame');
contentFrame.src = 'foo.html';
contentDiv.style.display='block';
}
I have noticed some weird behavior with IE and using innerHTML. I would only use it to clear the contents (innerHTML = ""). If I want to add anything, I use HTMLElement.appendChild(); it hasn't failed for me yet.

Have you tried changing the url in your generated iframe?
E.g.
var randomNum = Math.random();
var html = "<iframe src=\"bar.html?rand="+randomNum+"\" />";
Even better, combine that with geowa4's appendChild() suggestion.

Set the SRC of the Iframe instead of changing the innerHTML of its container:
html:
<iframe id="myFrame" src="about:blank" />
script:
document.getElementById('myFrame').src='foo.html'

Related

how can i use javascript to remove iframe's html tag?

I want to remove iframe's content but keep the "iframe tag" unchanged
like:
<iframe>
<html>
...
</html>
</iframe>
change to
<iframe>
</iframe>
I tried this:
var frame_node = document.getElementsByTagName("iframe")[0];
frame_node.removeChild(frame_node.firstChild);
But I got an error: frame_node.firstChild is not an object
So how to do this?
thx
got the answer:
document.getElementsByTagName("iframe")[0].contentWindow.doc‌​ument.getElementsByT‌​agName("html")[0].re‌​move();

How can I execute code in an iFrame's onload event?

I am currently using Ace (http://ace.c9.io/) to take code from an editor and execute it within an iFrame. My issue is that when I add something along the lines of
Code in Editor
<script type="text/javascript">
window.onload = function() {
alert("hello");
}
</script>
to the head or body of the iFrame, the code is never executed. This is my current code:
Injecting Code into iFrame
$("#btnRun").click(function(event) {
event.preventDefault();
// iFrame with id="preview"
var preview = $("#preview").contents();
// Get code from editor and wrap in <script> tags
var script = "<script type='text/javascript'>" + ace.edit("js-editor").getSession().getValue() + "</script>";
// Append code to head or body, in this case head
preview.find("head").append(script);
});
The code is successfully added to the iFrame, however it is never executed. I can also successfully add HTML/CSS and it displays in the iFrame, but the javascript is never touched.
I have tried wrapping the code in script tags within the editor only, as well as using an escape character on the closing tag: "</script>" but to no avail.
This is the iFrame in my index.html document.
iFrame in index.html
<iframe class="editor" id="preview" name="result" sandbox="allow-forms allow-popups allow-scripts allow-same-origin" frameborder="0">
#document
<!-- Editor content goes here -->
</iframe>
After the code is injected the iFrame looks like this
iFrame with Injected Code
<iframe class="editor" id="preview" name="result" sandbox="allow-forms allow-popups allow-scripts allow-same-origin" frameborder="0">
#document
<html>
<head>
<script type="text/javascript">
window.onload = function() {
alert("hello");
}
</script>
</head>
<body>
</body>
</html>
</iframe>
Also when calling the window.onload or window.top.onload event from within the iFrame, the code executes but only affects the page containing the iFrame and not the contents of the iFrame itself.
Thank you.
Note: When the code is not within window.onload it runs fine. However I wish to be able to execute this code when the frame's onload function is executed.
I would think that you are adding the JS to the iframe after the onload event has already fired.
Perhaps you could try simulating an event to run the preview code or dispatching the onload event again?
Might help: https://developer.mozilla.org/en-US/docs/Web/API/Window.dispatchEvent
I was able to fix this myself. The problem was that appending the script to be within the iFrame wasn't enough to make it work. To make the script only be executed within the iFrames DOM was to write directly to it.
$("#btnRun").click(function(event) {
event.preventDefault();
var previewDoc = window.frames[0].document;
var css = ace.edit("css-editor").getSession().getValue();
var script = ace.edit("js-editor").getSession().getValue();
var html = ace.edit("html-editor").getSession().getValue();
previewDoc.write("<!DOCTYPE html>");
previewDoc.write("<html>");
previewDoc.write("<head>");
previewDoc.write("<style type='text/css'>" + css + "</style>");
previewDoc.write("<script type='text/javascript'>window.onload = function() {" + script + "}</script>");
previewDoc.write("</head>");
previewDoc.write("<body>");
previewDoc.write(html);
previewDoc.write("</body>");
previewDoc.write("</html>");
previewDoc.close();
});
I think it would be more elegant to use the contentDocument property of the iframe, and then inject the script and trigger the parser so it actually interprets it as JavaScript.
I put up a small proof of concept on github. I hope it solves your problem in a more elegant manner.
https://github.com/opreaadrian/iframe-injected-scripts
Cheers,
Adrian.

calling an iframe inside a js function

I'm trying to create an external link, that appears within the same site.
Here, If I click on a link it should display the contents of that link(external site) within our site. i.e., if my site is siteA and in that I place a link (to siteB) that will redirect to 'siteB' closing 'siteA'. I just want to avoid the situation besides I want to make the siteB to be opened within the siteA
My idea is when the link is opened, an iframe will be created and the external site will be opened within that Iframe.
Google
<script type="text/javascript">
function executeOnClick(){
<iframe name="your_frame_name" src="www.google.com" > </iframe>
return true;
}
</script>
I wrote this code, but couldn't get what I expect. I tried to use button, but it's not working.
Is there any other way to fix my issue..
No javascript is needed, use target attribute:
Load the page
<iframe id="iframe1"> </iframe>
JSFiddle
IMPORTANT: you cannot display http://google.com in iframes because of their X-Frame-Options. See: The X-Frame-Options response header
function executeOnClick(){
$('body').append('<iframe name="your_frame_name" src="www.google.com" height=200 width=200 > </iframe>');
return true;
}
try this
The iframe markup should not be inside your JavaScript function. That does nothing except throwing an exception. Put the markup below your anchor and change its src on click:
Google
<iframe id="targetFrame"></iframe>
<script>
function executeOnClick(target) {
document.getElementById("targetFrame").src = target.src;
return false;
}
</script>
In fact you don't even need JavaScript to do this. You can use the target attribute of the anchor and set it to be the name of the frame you want to open the page in:
Google
<iframe name="targetFrame" id="targetFrame"></iframe>
Change to this:
onclick="executeOnClick(this); return false;"
and do this in your funcition:
<script type="text/javascript">
function executeOnClick(elem){
var frame = '<iframe name="your_frame_name" src="'+ elem.getAttribute('href') +'" > </iframe>';
document.body.appendChild(frame); // <----append it here.
}
</script>
In your onclick function you have to return false; to stop the default behaviour of an anchor to take you to the another page.
please note that the google.com will not work with iframe
Google
<iframe id="targetFrame"></iframe>
<script>
function executeOnClick(src) {
document.getElementById("targetFrame").src =src;
}
</script>
<iframe src="www.google.com" height="400" width="551" frameborder="0" scrolling="no" runat="server"></iframe>
Use runat attribute too. Hope this works.
If doesn't, what's the error?

iframe src to be massaged by javascript

To say that I am a novice in javascript is an insult to a novice. Even my limited HTML knowledge is self-taught. Here's my problem: I am trying to massage the src in a simple iframe, like so:
<html>
<head>
<script type="text/javascript">
function embedKey() {
var url = window.location.href;
var symbol = url.split('?')[1];
if(symbol=="INNO"){
uniqueKey = "&resid=27A14C5DE396792C%21235&authkey=ANDfOBKrOKskLqg"
return "https://skydrive.live.com/embed?cid=27A14C5DE396792C" + uniqueKey +"&em=2&wdAllowInteractivity=False&ActiveCell='Sheet1'!B3&wdHideGridlines=True&wdHideHeaders=True"
}
else {
alert(url);
return false;
}
}
</script>
</head>
<body>
<iframe width="402" height="346" frameborder="0" scrolling="no" src=javascript:embedKey();></iframe>
</body>
</html>
I will be adding many more conditions/symbols/return strings to the embedKey() function. Right now, I am trying to make it work with one.
I don't think JavaScript gets executed from a src attribute like that. With something like an href attribute on an a element (where one often sees inline JavaScript) there's at least a click event to respond to, but not in this case.
Instead of trying to call the function inline from the element like that, call it from a script block after the element has loaded. Something like this:
<iframe width="402" height="346" frameborder="0" scrolling="no" id="someIframe"></iframe>
<script type="text/javascript">
document.getElementById('someIframe').src = embedKey();
</script>

remove/replace specific HTML from inside iframe using Javascript

Okay so in my page I have an iframe element which will load HTML that will always have a specific line of HTML code in it that I need to replace when the iframe is loaded. The iframe src will vary so it has to be done as the iframe is loaded. The HTML I want to replace is in the file that's loaded by the iframe and it will look something like this:
<div class="myclass1" style="height:XXXpx; width:YYYpx;">
So what I need is actually for every div that has class="myclass1" to have the height attribute of the style stripped and the width kept whatever it was. All "myclass1" divs will follow this format. So I want to replace all lines like that with this:
<div class="myclass1" style="width:YYYpx;">
I'm not very experienced with javascript at all really so any help, even just pointers, is appreciated because I don't know how to start of even if this is possible.
If the src of the iframe is on the same domain, use this :
var iFrame = document.getElementById("your-iframe-id");
if ( iFrame.contentDocument )
{
iFrameDocument = iFrame.contentDocument;
}
else if ( iFrame.contentWindow )
{
iFrameDocument = iFrame.contentWindow.document;
}
The use iFrameDocument.getElementById or whatever you need
You can use the following example for change the styles of loaded div,Call the javascript function after loading the page .
<html>
<head>
<script type="text/javascript">
function change_style()
{
document.getElementById("div_id").style.width="yyypx";
}
</script>
</head>
<body>
<div id="div_id" class="myclass1" style="height:XXXpx; width:YYYpx;">
-------------------
-------------------
</div>
<script>
change_style();
</script>
</body>
</html>

Categories

Resources