Renaming Iframes with javascript - javascript

I am trying to figure out how to name/rename iframes with javascript.
function sesamOpenU(){
x = document.querySelector('iframe');
x.style.height= '200px';
x.style.width= '400px';
x.name = 'myFrame1' ;
let url = 'https://www.example.com/'
let other = window.open(url,'myFrame');
}
<iframe name ="myFrame">
</iframe>
<button onclick= "sesamOpenU()">Sesam, open U</button>
First, i tried to name an iframe without a name with x.name after defining x.
no errors in the console, but no result either.
I named the iframe manually to target it, and it works.
Then I tried to rename it with Javascript, but again, no result.
For ruling things out, I decided to adjust the height and width for reference to see if it would adjust.
It does.
I tried the adjustments before the function, no result. (widht and heigh does, name doesn't)
Can someone shine a light on my problem?
Edit: yes, i know that i have targeted myFrame, and not myFrame1 in the example. It was the last step of testing which one it would take. The named version, or the renamed version. The named version works, the renamed version doesn't ( opens the webpage in a new tab)
edit: solved.

Testing locally showed differences between Firefox and Chrome - Firefox happily opened the url supplied to window.open in the iframe with the same name as the browsing context supplied as the second argument. Chrome did not and would open the url in a new tab.
A possible workaround might be to set the src attribute of the iframe element directly:
function sesamOpenU(){
x = document.querySelector('iframe');
x.style.height= '200px';
x.style.width= '400px';
x.name = 'myFrame1' ;
let url = 'https://www.example.com/'
// let other = window.open(url,'myFrame1');
x.src = url;
}
This seems to work in both Firefox and Chrome, whether using example.com or the business site url provided in the original posted.

The code does reassign the name of your iframe but the way you set the source does not seem to be working.
I tried the following which seem to be working:
function sesamOpenU(){
x = document.querySelector('iframe');
x.style.height= '200px';
x.style.width= '400px';
x.name = 'myFrame1' ;
let url = 'https://www.example.com/';
x.src = url;
}
<iframe name ="myFrame">
</iframe>
<button onclick= "sesamOpenU()">Sesam, open U</button>

Note: your code does not work in an SO snippet, at least on my system, it gives this error:
js:26 Blocked opening 'https://www.alternate.nl/' in a new window
because the request was made in a sandboxed frame whose 'allow-popups'
permission is not set.
So I have tried it as a complete piece of code, see below.
It works fine with renaming the iframe - as long as you go back to having a url that will allow itself to be in a iframe - somehow your original url has been replaced by one that won't work - and whether or not the iframe had another name to begin with. Maybe there was some typo problem in the original code given which we missed? Anyway, all is well:
Here is the full code:
<!doctype html>
<html>
<head>
<title>Test iframe</title>
</head>
<body>
<iframe name='myFrame'></iframe>
<button onclick= "sesamOpenU()">Sesam, open U</button>
<script>
function sesamOpenU(){
x = document.querySelector('iframe');
x.style.height= '200px';
x.style.width= '400px';
x.name = 'myFrame1' ;
let url = 'https://www.alternate.nl/'
let other = window.open(url,'myFrame1');
}
</script>
</body>
</html>

Related

Create an iframe with only javascript

I have been struggling on one of those programing challenge sites for a while. It has a console type thing that lets me enter javascript and press a run button. I need to create an iframe inside of that webpage with another webpage inside of it (for example, im on thiswebsite.com/level1 and I need to create the iframe with thiswebsite.com/level2 inside of it).
Have tried creating iframes as follows:
document.getElementById('someDiv').innerHTML = '<iframe src="thissite.com/level2/" height= 300 width=400>';
However it does not run when I try this, is there an alternative way?
Thanks.
Use createElement method of document
var a = document.createElement('iframe');
a.src = "your path will go here"; //add your iframe path here
a.width = "1000";
a.height = "500";
document.querySelector('body').appendChild(a)
I just append the iframe to body. To append it to someDiv replace last line with below code
document.getElementById('someDiv').appendChild(a);
I doubt that the site doesn't allow you to create iframes.
Like, if you try the below code in your Console
//define function
function prepareiFrame() {
var ifrm = document.createElement("iframe");
ifrm.setAttribute("src", "https://google.com/");
ifrm.style.width = "640px";
ifrm.style.height = "480px";
document.body.appendChild(ifrm);
}
//call it
prepareiFrame()
Stackoverflow will throw the below error:
Refused to display 'https://www.google.co.in/?gfe_rd=cr&ei=OoWPV7agCuHt8wf3v6egDA' in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'.

How to store iframe in a variable?

<html>
<body>
<iframe id="src">
</body>
</html>
I want to have the iframe show up in the div element through a Javascript function but I can't seem to figure out what isn't working. Any ideas?
document.getElementById('site').src = http://www.w3schools.com/;
Thanks in advance!
Try
document.getElementById('src').src = 'http://www.w3schools.com/';
a) the url should be provided as string (quoted)
b) the id of your iframe is src not site
Your iframe don't have the id site, so your code won't have any effect.
(Also please note that you didn't close the iframe tag) .
Here's the right code (fiddle) .
<input type="button" onclick="changeIframeSrc('myFrame');" value="changeSrc">
<iframe src="http://www.example.com" id="myFrame"></iframe>
<script>
function changeIframeSrc(id) {
e = document.getElementById(id);
e.src = "http://www.wikipedia.com/";
}
</script>
First, a couple small things:
the id on your iframe appears to be src and not site; and
you need to close the iframe tag.
Assuming that you're just dealing with one iframe and it has an id then by all means:
var myIframe = document.getElementById('src');
// gives you just that one iframe element
You may want to consider document.querySelectorAll though, in case you're working with more than one iframe.
var iframes = document.querySelectorAll('iframe');
See that in action: http://jsbin.com/equzey/2/edit
And important side note: if all you need is access to the iframe element (e.g., to manipulate its source or to apply CSS via the style attribute) then the above should be fine. However, if you need to work with the contents of the iframe, you'll need to get inside its web page context with the contentWindow property:
var iframes = document.querySelectorAll('iframe');
iframes[0].contentWindow;

set innerHTML of an iframe

In javascript, how can I set the innerHTML of an iframe? I mean: how to set, not get.
window["ifrm_name"].document.innerHTML= "<h1>Hi</h1>" does not work, and the same for other solutions.
Iframe and parent document are on the same domain.
I would need to set html of the whole document iframe, not its body.
I would need to avoid jquery solution.
A really simple example ...
<iframe id="fred" width="200" height="200"></iframe>
then the following Javascript is run, either inline, part of an event, etc ...
var s = document.getElementById('fred');
s.contentDocument.write("fred rules");
the "contentDocument" is the equivalent of the "document" you get in the main window, so you can make calls against this to set the body, head, any elements inside ... etc.
I've only tested this in IE8, Chrome and Firefox ... so you may want to test in IE6/7 if you have copies available.
In Firefox and Chrome (don't know about Opera), you can use the data: URI scheme.
<iframe src=".... data: URI data here ......">
JSFiddle example
Here is a tool to generate data:URI encoded data.
This does not work in IE:
For security reasons, data URIs are restricted to downloaded resources. Data URIs cannot be used for navigation, for scripting, or to populate frame or iframe elements.
If however as you say in the comment, getting/setting the document's body is enough, you are much easier off using one of the linked examples.
There is also the srcdoc attribute:
<iframe srcdoc="<p><h1>Hello</h1> world</p>"></iframe>
Demo, Polyfill.
In improving my file uploads in an AJAXS env I had the same need. This worked for me in ie8 and ff 22.0. Both the body innerhtml and div innerhtml work.
function copyframedata(data) {
var x = document.getElementById("photo_mgr_frame");
var y = x.contentWindow || x.contentDocument;
if (y.document) y = y.document;
y.getElementById('photo_mgr_mb').innerHTML = data;
}
got it from w3
I came across the same problem but here's an easy fix.
function Run(){
var txt = "<h1>Hello World</h1>";
var frame = document.getElementById('frame');
var frame = (frame.contentWindow || frame.contentDocument);
if (frame.document) frame = frame.document;
frame.open();
frame.write(txt);
frame.close();
}
<iframe id='frame'>
</iframe>
<button onclick='Run()'>Run</button>

DHTML, iFrame and IE

I've got a piece of JavaScript that inserts/removes an iframe from the DOM. Everything is dandy in Chrome and FireFox but the iframe is not displayed in IE. The code below is the creation and insertion. When inspecting with a Developer tools I can see that the iframe is part of the DOM exactly as I expected it to be. Any suggestion on what might cause it not to be displayed?
function getiFrame(target) {
var frame = document.getElementById(target);
if (null == frame) {
frame = document.createElement("iframe");
frame.setAttribute("width", "100%");
frame.setAttribute("height", "1000px");
//frame.setAttribute("frameborder", "0");
frame.setAttribute("id", target);
frame.setAttribute("name", target);
frame.setAttribute("src", "http://dmi.dk");
} else {
frame.src = "http://dmi.dk";
frame.style.visibility = "visible";
}
return frame;
}
var frame = getiFrame(target);
var row = document.getElementById(contentRowId);
for (var i = 0; row.childNodes.length > 0; i++) {
row.removeChild(row.childNodes[0]);
}
row.appendChild(frame);
EDIT:
To clarify I've tryed setting the attributes directly (as suggested by Tim Down) the above was the result of my desperate attempts.
Further when inspecting the DOM I get a perfectly valid iframe tag:
<iframe propdescname="full" width="100%" height="1000" id="full" src="http://dmi.dk">
and inspecting that also shows that it's read and parsed the src (http://dmi.dk) correctly. I can inspect the DOM of that site too.
So what puzzles me is that when everything seems to work. What might stop it from being displayed.
There's one obvious problem:
frame = document.createElement("div");
should be
frame = document.createElement("iframe");
Also, setAttribute is unnecessary, verbose and error-prone in IE. Use DOM properties instead:
frame.width = "100%";
frame.height = 1000;
//frame.frameBorder = 0;
frame.id = target;
frame.name = target;
frame.src = "http://vrk.dk";
Jim Coplien referres to this as the Rubber Duck pattern. "You cannot ask xx before You've consulted the rubber duck". Who hasn't solved there own question while asking some one for advice.
I'was editing my post writing that the iframe was in a td and came to think that I hadn't made sure it actually was. The issue turned out to be me removing the td and inserting the iframe into the tr which IE incidentally handles differently when done dynamically than when done statically.
Thanks for listening in, playing the role of "the rubber duck"

IE 8 iframe border

There is a border showing on an iframe and I can't get rid of it.
IE 6 and 7 work as intended with a little JavaScript:
function test(){
var iframe = document.getElementById('frame2');
iframe.contentWindow.document.body.style.backgroundColor = "#a31d1d";
iframe.contentWindow.document.body.style.border = "#a31d1d";
iframe.contentWindow.document.body.style.outlineColor = "#a31d1d";
}
But the border remains visible in IE 8.
Add following attributes to iframe tag:
marginheight="0" marginwidth="0" frameborder="0"
I had the same problem with iframes created dynamically, and it turned out that setting border properties AFTER adding the iframe to the document has NO effect:
The following code shows a 3d border:
var iframe = document.createElement("IFRAME");
iframe.src = "http:www.stackoverflow.com";
//Iframe added BEFORE setting border properties.
document.body.appendChild(iframe);
iframe.frameBorder = "no";
But this actually removes it:
var iframe = document.createElement("IFRAME");
iframe.src = "http:www.stackoverflow.com";
iframe.frameBorder = "no";
//Iframe added AFTER setting border properties.
document.body.appendChild(iframe);
Hope that this would help solve your problem.
I tried loads of variations on this idea and ended up using something along these lines. Thought I'd share it.
<script type="text/javascript">
url = 'http://www.dollypower.com';
title = 'Dolly Power';
width = '660';
height = '430';
document.write('<iframe src='+url+' title='+title+' width='+width+' height='+height+' frameborder=0></iframe>');
</script>
Then I used noscript tags to enter an alternative for non-JS users, i.e:
<noscript><p>Please click here for Dolly Power</p></noscript>
I tested it in IE8 and it's all cool for me and it also validates.
Hope this might help someone out there!
Success!
Try this. It will find any iframe elements and remove their borders in IE and other browsers (though you can just set a style of "border : none;" in non-IE browsers instead of using JavaScript). AND it will work even if used AFTER the iframe is generated and in place in the document (e.g. iframes that are added in plain HTML and not JavaScript)!
This appears to work because IE creates the border, not on the iframe element as you'd expect, but on the CONTENT of the iframe--after the iframe is created in the BOM. ($#&*##!!! IE!!!)
Note: The IE part will only work (of course) if the parent window and iframe are from the SAME origin (same domain, port, protocol etc.). Otherwise the script will get "access denied" errors in the IE error console. If that happens, your only option is to set it before it is generated, as others have noted, or use the non-standard frameBorder="0" attribute. (or just let IE look fugly--my current favorite option ;) )
Took me MANY hours of working to the point of despair to figure this out...
Enjoy. :)
// =========================================================================
// Remove borders on iFrames
if (window.document.getElementsByTagName("iframe"))
{
var iFrameElements = window.document.getElementsByTagName("iframe");
for (var i = 0; i < iFrameElements.length; i++)
{
iFrameElements[i].frameBorder="0"; // For other browsers.
iFrameElements[i].setAttribute("frameBorder", "0"); // For other browsers (just a backup for the above).
iFrameElements[i].contentWindow.document.body.style.border="none"; // For IE.
}
}
Sample HTML to go with the sample JS would be helpful =)
Try using IE8's Developer Tools (press F12 on the page you have problems with) to isolate what styles are being applied to the iframe. You can also play with the styles there, to cut down your iteration time.
Keep in mind that this may be IE not respecting border settings in the css, whereas the traditional setting of the attribute BORDER=0 on the iframe element may work. Worth a test, at least.
Edit: It looks like what does fix the problem is setting frameborder='0' on the iframe element. That worked for me, at least.
If you want your code to validate you could do this with javascript. I found the perfect answer when I had this problem a few months ago here
var iframe = document.createElement("iframe");
iframe.src = "banner_728x90.gif";
iframe.width = "728";
iframe.height = "90";
iframe.frameBorder = "0";
iframe.scrolling = "no";
document.body.appendChild(iframe);
f you want to load another page seamless in the iframe you can do this if you copy and paste this code into the head of your page. I found it on a site with free scripts. The performance is good in most cases
function getDocHeight(doc) {
doc = doc || document;
var body = doc.body, html = doc.documentElement;
var height = Math.max( body.scrollHeight, body.offsetHeight, html.clientHeight, html.scrollHeight, html.offsetHeight );
return height;
}
function setIframeHeight(id) {
var ifrm = document.getElementById(id);
var doc = ifrm.contentDocument? ifrm.contentDocument: ifrm.contentWindow.document;
ifrm.style.visibility = 'hidden';
ifrm.style.height = "10px"; // reset to minimal height in case going from longer to shorter doc
ifrm.style.height = getDocHeight( doc ) + 10 + "px";
ifrm.style.visibility = 'visible';
}
You then give your iframe an id and call the script on load. This is how.
var iframe = document.createElement("iframe");
iframe.setAttribute('id', "ifrm1");
iframe.setAttribute('src', 'http://www.hekcmviw.com/'); // change the URL
iframe.setAttribute('width', '100%');
iframe.setAttribute('height', '10');
iframe.setAttribute('frameBorder', '0');
iframe.setAttribute('scrolling', 'no');
iframe.setAttribute('onload' ,"setIframeHeight(this.id)");
document.body.appendChild(iframe);

Categories

Resources