setAttribute iFrame name and Chrome - javascript

Here is a simple setAttribute for an iFrame to append a name.
Issue is that the below code works great in all browsers except Chrome.
<iframe id="frame" frameborder="0" src="http://website.ca/"></iframe>
Parent javascript:
(function() {
var newFrameName = "hello";
document.getElementById("frame").setAttribute("name", newFrameName);
})();
in the iFrame:
var iframeName = window.name;
alert (iframeName );
Alert calls "Hello" in all browsers, Chrome calls "frame" -- which is the ID of the iFrame.
looking at source (through the elements inspector), in Chrome, I see the correct name for the iFrame: name="Hello" ... but the alert calls the id.
why would that be? I'm i missing anything?

Creating iframe by createElement fixes the issue:
function createFrame() {
frame= document.createElement("iframe");
frame.setAttribute("src", "https://website.ca/");
frame.setAttribute("name", "Hello");
frame.setAttribute("id", "frame");
frame.frameBorder = 0;
frame.style.width = 100 + "%";
frame.style.height = 2300 + "px";
document.getElementById("iframeHolder").appendChild(frame);
}
createFrame();
<div id="iframeHolder"> </div>
Bit of a hack, but it works for this situation.

6 and a half years later I ran into the same problem.
It seems that Chrome sets the window.name property once and doesn't update it when the enclosing iFrame's name (either property or attribute) is updated.
Setting the window.name directly does work however.
So, changing the OP's example from:
(function() {
var newFrameName = "hello";
document.getElementById("frame").setAttribute("name", newFrameName);
})();
into
(function() {
var newFrameName = "hello";
document.getElementById("frame").name = newFrameName; // keep for other browsers
document.getElementById("frame").contentWindow.name = newFrameName;
})();
works...

Related

Why does calling a function onclick not work all the time in Chrome and FF, but works in IE?

I have the below code:
<HTML>
<HEAD>
<SCRIPT>
function myFunction(atlasTrackingURL)
{
var atlasURL = atlasTrackingURL;
if (!atlasURL) return;
//Build a cache busting mechanism
var timestamp = new Date();
var queryString = "?random=" + Math.ceil(Math.random() * 999999999999) +
timestamp.getUTCHours() + timestamp.getUTCMinutes() +
timestamp.getUTCSeconds();
//Build the final URL
atlasURL = atlasURL + queryString;
if (!document.getElementsByTagName || !document.createElement
|| !document.appendChild)
{return false;}
else
{ //Activate the JACTION call
var script = document.createElement("script");
script.type = "text/javascript";
script.src = atlasURL;
document.getElementsByTagName("head")[0].appendChild(script);
return true;
}
}
</SCRIPT>
</HEAD>
<BODY>
Test - Click Me
</BODY>
</HTML>
It works in Internet Explorer every time, but rarely works in Chrome and Firefox. Why would this be?
Can these browsers not handle a function onClick very well? Are there any other options I can take?
I am trying to help a client figure out why one of their tracking tags are not firing off all the time on click in these browsers.
Thanks,
You've got some kind of browser-dependent race condition going on, as Musa pointed out.
Try hiding the link initially, waiting for the document to load, and then adding the onclick attribute and revealing the link with javascript.
So, for example, change the link HTML to something like:
<a id="microsoft-link" href="http://www.microsoft.com" style="display: none;">Test - Click Me</a>
And add in your javascript, below the myFunction(), something like:
document.addEventListener('DOMContentLoaded', function(){
var link_elem = document.getElementById("microsoft-link");
link_elem.onclick = function() {
myFunction('http://view.atdmt.com/jaction/adoakb_PiggybackJSTest_1');
};
link_elem.style.display = 'inherit';
});
jsfiddle -- http://jsfiddle.net/m8VTy/3/
edit: I realized I may be misinterpreting what you're trying to do. What exactly is myFunction() supposed to accomplish ?

assigning variable to document.getElementById().Innerhtml not working

See the code below:
var text=["yuppie", "kkkoseh", "watchdog"];
var messageIndex=0;
function looptext (){
var MessageElement= document.getElementById("happy").innerHTML
var Message=text[messageIndex];
MessageElement=Message;
messageIndex++;
if(messageIndex>=text.length){
messageIndex=0;
}
}
window.onload = function() {
setInterval(looptext, 1000);
};
It doesn't work.
But when I remove .innerhtml at variable MessageElement and set the MessageElement.innerHtml= Message , it works.
Why is it so?
Sorry, I am a newbie learning JavaScript.
Because that's how variables and values work in JavaScript. Imagine variables to be like containers. With
var MessageElement = document.getElementById("happy").innerHTML
the container MessageElement will contain a string. Later on, with
MessageElement = Message;
you simply put a new value in the container, overwriting the previous value/content the container had. But it doesn't have any effect on the location where the previous value was coming from.
But when I remove .innerhtml at variable MessageElement and set the MessageElement.innerHtml= Message , it works.
Now the variable contains a reference to the DOM element and
MessageElement.innerHtml = Message
doesn't assign a new value to the variable (doesn't put a new value in the container), it uses the value of the variable (container).
innerHTML return a string not e pointer to the document.getElementById("happy")'s text node.
try this
var text=["yuppie", "kkkoseh", "watchdog"];
var messageIndex=0;
function looptext (){
document.getElementById("happy").innerHTML = text[messageIndex];
messageIndex++;
if(messageIndex>=text.length){
messageIndex=0;
}
}
window.onload = function() {
setInterval(looptext, 1000);
};
#Felix King is correct.
To test how it is actually behaving I myself tried the below snippet on W3Schools.
And I found:
var MessageElement = document.getElementById("happy") - assigns the element (in my example - http://www.microsoft.com/)
alert(m) thus displays - http://www.microsoft.com/
m.innerHTML = "Atul" - assigns Atul to the element.
However, value of m was still http://www.microsoft.com/ as Felix rightly said - 'MessageElement.innerHtml = Message, doesn't assign a new value to the variable'.
<html>
<head>
<script>
function changeLink()
{
var m = document.getElementById("myAnchor"); //assigns http://www.microsoft.com/
alert(m); //
m.innerHTML = "Atul"
alert(document.getElementById("myAnchor").innerHTML + " new");
document.getElementById('myAnchor').innerHTML=m;
}
</script>
</head>
<body>
<a id="myAnchor" href="http://www.microsoft.com">Microsoft</a>
<input type="button" onclick="changeLink()" value="Change link">
</body>
</html>
Thanks Felix :)

How to set HTML content into an iframe

I have a HTML string
<html>
<body>Hello world</body>
</html>
and I want to set it to an iframe with JavaScript. I am trying to set the HTML like this:
contentWindow.document.body.innerHTML
or
contentDocument.body.innerHTML
or
document.body.innerHTML
but IE gives "Access is denied." or "Object does not support this property or method." or "Invalid final element to the action." errors.
Here is my full code:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="jquery_1.7.0.min.js"/>
<script type="text/javascript">
$(document).ready(function(){
var htmlString = "<html><body>Hello world</body></html>";
var myIFrame = document.getElementById('iframe1');
// open needed line commentary
//myIFrame.contentWindow.document.body.innerHTML = htmlString;
//myIFrame.contentDocument.body.innerHTML = htmlString;
//myIFrame.document.body.innerHTML = htmlString;
//myIFrame.contentWindow.document.documentElement.innerHTML = htmlString;
});
</script>
</head>
<body>
<p>This is iframe:
<br>
<iframe id="iframe1">
<p>Your browser does not support iframes.</p>
</iframe>
</body>
</html>
You could use:
document.getElementById('iframe1').contentWindow.document.write("<html><body>Hello world</body></html>");
Here's a jsFiddle, which works in all major browsers.
Note that instead of contentDocument.write you should use contentWindow.document.write: this makes it work in IE7 as well.
var htmlString="<body>Hello world</body>";
var myIFrame = document.getElementById('iframe1');
myIFrame.src="javascript:'"+htmlString+"'";
With html5 you'll be able to use the srcdoc attribute.
The innerHTML is a bit tricky especially in IE, where elements like thead are read-only and cause a lot of trouble.
Based on the documentation on msdn you might try documentMode which provides a innerHTML property.
myIFrame = myIFrame.contentWindow ||
myIFrame.contentDocument.document ||
myIFrame.contentDocument;
myIFrame.document.open();
myIFrame.document.write('Your HTML Code');
myIFrame.document.close();
this might only work in IE.
http://msdn.microsoft.com/en-us/library/ie/ms535862(v=vs.85).aspx
http://msdn.microsoft.com/en-us/library/ie/cc196988(v=vs.85).aspx
http://msdn.microsoft.com/en-us/library/ie/ms533897(v=vs.85).aspx
How about document.documentElement.innerHTML. But do know that everything in the page will be replaced even the script that does that.
For an iframe it would be like this myIFrame.contentWindow.document.documentElement.innerHTML
I have a problem with 'origin' with the answers here. This is how it's work for me:
const frame1 = document.createElement('iframe');
frame1.name = 'frame1';
//not have to set this style,just for demo
frame1.style.position = 'absolute';
frame1.style.height = '800px';
frame1.style.top = '100px';
frame1.style.left = '100px';
frame1.style.background = 'white';
document.body.appendChild(frame1);
const frameDoc =
frame1.contentWindow || frame1.contentDocument.document ||
frame1.contentDocument;
frameDoc.document.write('<html><head><title></title><body>Hello world</body></html>');
frameDoc.document.close();
In 2023, the correct answer to this problem is to use the srcdoc attribute of the <iframe> element. I can be done straight in your HTML file or with javascript:
document.getElementById('iframe').srcdoc = "<html><body>Hello world!</body></html>";
try it:
$('iframe').load(function() {
$(this).contents().find('body').append("Hello world");
});
update:
$(function(){
$('iframe').load(function() {
$(this).contents().find('body').append("Hello world");
});
})

Correct access of dynamic iFrame in IE

Plain JS - please no jQuery suggestions - it is for a bookmarklet that needs to use as plain JS as possible.
I hope someone KNOWS the answer since I cannot reliable create a fiddle.
This code will run in the scope of the page it is inserted in - it works perfectly in Fx6-9, safari and latest Chromes on Windows XP and OSX - Only IE gives me undefined when I try to access the iFrame
var zContainer = document.getElementById('zContainer');
if (zContainer==null) {
zContainer = document.createElement("div");
zContainer.id="zContainer";
document.body.appendChild(zContainer);
}
var zStuff = {}; // minimise window var footprint
zStuff.html = '<body>Hello</body>';
if (!zFrame) { // did we already have one?
zFrame = document.createElement("iframe");
zFrame.id="zIframeId"; zFrame.name="zIframeName"; zFrame.frameBorder="0";
zIFS = zFrame.style; zIFS.border="0"; zIFS.width="500px"; zIFS.height="500px"; zIFS.backgroundColor="white"; zIFS.display="block";
zContainer.appendChild(zFrame); // append to div
zFrame = window.frames["zIframeName"]; // undefined in IE8 !!!!!
// zFrame = document.getElementById("zIframeId"); // undefined in IE8 !!!!!
zFrame.src="javascript:'<body></body>'"; // initialise body
zFrame.document.write(zStuff.html); // or zFrame.contentDocument.write
zFrame.document.close();
// zFrame.document.body.innerHTML=zStuff.html; // also does not work
// zFrame.src="javascript:'"+zStuff.html+"'"; // alternative method - either one works in Fx/Chrome
}
Thanks for any hints and for not voting this down. I hope the SO community will be as
helpful to me as I have been to it over the last year and a half...
Update - since the code I posted had some remnants of desperation, I changed it to
if (!zFrame) { // did we already have one?
zFrame = document.createElement("iframe");
zFrame.id="zIframeId"; zFrame.name="zIframeName"; zFrame.frameBorder="0";
zIFS = zFrame.style; zIFS.border="0"; zIFS.width="500px"; zIFS.height="500px"; zIFS.backgroundColor="white"; zIFS.display="block";
zContainer.appendChild(zFrame); // append to div
zFrame.src="javascript:'<body></body>'"; // initialise body
zFrame.document.write(zStuff.html); // or zFrame.contentDocument.write
zFrame.document.close();
}
the above now replaces the page I am on with the code in the zStuff.html
instead of replacing only the iFrame content - it also broke in Fx
Now I have to do this in Fx which IE also does not mind but still replaces the window and not the iFrame
if (!zFrame) {
zFrame = document.createElement("iframe");
zFrame.scrolling="no"; zFrame.id="zIframeId"; zFrame.name="zIframeName"; zFrame.frameBorder="0";
zIFS = zFrame.style; zIFS.border="0px none"; zIFS.width="549px"; zIFS.height="510px"; zIFS.backgroundColor="white"; zIFS.display="block";
zDRContainer.appendChild(zFrame);
zFrame.src="javascript:'<body></body>'";
setTimeout(function() {
var zFrame = window.frames["zIframeName"]; // this is needed for the document.write
zFrame.document.write(zStuff.html);
zFrame.document.close();
},100);
}
The hack I suggested in chat:
var a = setInterval( function(){
try{
zFrame.contentWindow.document.write(zStuff.html);
zFrame.contentWindow.document.close();
clearInterval(a);
}
catch(e){}
}, 10 );
Since it is not known when IE allows accessing contentWindow properties, this will keep trying until it is allowed.

Jquery attr('src') undefined in IE 8 (works in FF)

This has gotten so far,that I will sum up what we found out:
Inside the event handler the attribute src cannot be read in IE8 (FF works fine), neither with jQuery nor with usual javascript
The only way to get the data was to get it outside the handler, write it to an array and read it afterwards from the inside of the handler
But there was still no possibility to write to src (neither jQuery nor javascript worked - only for IE 8)
I've got it working by writing the img elemts themselves to the document, but the reason behind this problem is no solved
The snippet we have is used twice.
The old code
<script type="text/javascript">
jQuery(document).ready(function() {
//...
//view entry
jQuery('.blogentry').live('click',function(){
// Get contents
blogtext = jQuery(this).children('.blogtext').html();
blogauthor = jQuery(this).children('.onlyblogauthor').html();
blogtitle = jQuery(this).children('.blogtitle').html();
profileimage = jQuery(this).children('.profileimage').html();
imgleft = jQuery(this).children('.Image_left').attr('src');
imgcenter = jQuery(this).children('.Image_center').attr('src');
imgright = jQuery(this).children('.Image_right').attr('src');
// Write contents
jQuery('#bild_left').attr('src', imgleft);
jQuery('#bild_center').attr('src', imgcenter);
jQuery('#bild_right').attr('src', imgright);
jQuery('.person').attr('src', profileimage);
jQuery('#g_fb_name').html(blogauthor);
jQuery('#g_titel').html(blogtitle);
jQuery('#g_text').html(blogtext);
//...
});
//...
// Change entry
jQuery('.blogentry').each(function(){
entryindex = jQuery(this).attr('rel');
if (entry == entryindex)
{
// The following works fine (so 'children' works fine):
blogtext = jQuery(this).children('.blogtext').html();
blogauthor = jQuery(this).children('.onlyblogauthor').html();
blogtitle = jQuery(this).children('.blogtitle').html();
profileimage = jQuery(this).children('.profileimage').html();
// This does not work - only in IE 8, works in Firefox
imgleft = jQuery(this).children('.Image_left').attr('src');
imgcenter = jQuery(this).children('.Image_center').attr('src');
imgright = jQuery(this).children('.Image_right').attr('src');
//alert: 'undefined'
alert(jQuery(this).children('.Image_center').attr('src'));
//...
}
}
//...
});
</script>
The new code
Please see my own posted answer for the new code.
UPDATE:
This does not work if called inside of the click event!!!
jQuery('.Image_left').each(function(){
alert(jQuery(this).attr('src'));
});
SOLUTION TO GET THE IMAGE DATA:
relcounter = 1;
imgleft_array = new Array();
jQuery('.Image_left').each(function(){
imgleft_array[relcounter] = jQuery(this).attr('src');
relcounter++;
});
relcounter = 1;
imgcenter_array = new Array();
jQuery('.Image_center').each(function(){
imgcenter_array[relcounter] = jQuery(this).attr('src');
relcounter++;
});
relcounter = 1;
imgright_array = new Array();
jQuery('.Image_right').each(function(){
imgright_array[relcounter] = jQuery(this).attr('src');
relcounter++;
});
//... inside the eventhandler (entryindex = 'rel' of blogentry):
imgleft = imgleft_array[entryindex];
imgcenter = imgcenter_array[entryindex];
imgright = imgright_array[entryindex];
This works because it is not called inside the event handler and the sources are saved beforehand
BUT! I still cannot write the data, which is my aim:
jQuery('#bild_left').attr('src', imgleft);
jQuery('#bild_center').attr('src', imgcenter);
jQuery('#bild_right').attr('src', imgright);
UPDATE!!!
This is just crazy, I tried to write the data via usual javascript. This also works in FF, but no in IE8. Here really is some serious problem witt the attribute src:
document.getElementById('bild_left').src = imgleft;
document.getElementById('bild_center').src = imgcenter;
document.getElementById('bild_right').src = imgright;
alert(document.getElementById('bild_left').src);
This works in FF, but not in IE8, the attribute src remains undefined after writing! This seems to be not a jQuery problem at all!
children looks for immediate child elements only where as find looks for all the elements within it until its last child element down the dom tree. If you are saying find is working that means the element you are looking is not its immediate children.
Try to alert this jQuery(this).children('#Image_center').length see what you get.
FYI. Even when any element is not found jQuery will return an emtpy object it will never be null. So alert an emtpy object will always give you [object Object]. You should alwasy check for the length property of the jQuery object.
Try this
alert(jQuery(this).find('#Image_center').length);//To check whether element is found or not.
Bing Bang Boom,
imgright = jQuery(".Image_right",this).attr('src');
And why don't you easily use one working?
alert(jQuery(this).children('#Image_center').attr('src'));
change children to find
alert(jQuery(this).find('#Image_center').attr('src'));
It is probably the easiest solution, and when it work, why wouldn't you use it?
the problem is not in the attr('src') but in something else. The following snippet works in IE8:
<img id="xxx" src="yrdd">
<script type="text/javascript">
alert($('#xxx').attr('src'));
</script>
But if you for example change the the text/javascript to application/javascript - this code will work in FF but will not work in IE8
This has gotten so far,that I will sum up what we found out:
Inside the event handler the attribute src cannot be read in IE8 (FF works fine), neither with jQuery nor with usual javascript
The only way to get the data was to get it outside the handler, write it to an array and read it afterwards from the inside of the handler
But there was still no possibility to write to src (neither jQuery nor javascript worked - only for IE 8)
I've got it working by writing the img elemts themselves to the document, but the reason behind this problem is no solved
The new code
relcounter = 1;
imgleft_array = new Array();
jQuery('.Image_left').each(function(){
imgleft_array[relcounter] = jQuery(this).attr('src');
relcounter++;
});
relcounter = 1;
imgcenter_array = new Array();
jQuery('.Image_center').each(function(){
imgcenter_array[relcounter] = jQuery(this).attr('src');
relcounter++;
});
relcounter = 1;
imgright_array = new Array();
jQuery('.Image_right').each(function(){
imgright_array[relcounter] = jQuery(this).attr('src');
relcounter++;
});
//view entry
jQuery('.blogentry').live('click',function(){
// Get contents
entryindex = jQuery(this).attr('rel');
blogtext = jQuery(this).children('.blogtext').html();
blogauthor = jQuery(this).children('.onlyblogauthor').html();
blogtitle = jQuery(this).children('.blogtitle').html();
profileimage = jQuery(this).children('.profileimage').html();
imgleft = imgleft_array[entryindex];
imgcenter = imgcenter_array[entryindex];
imgright = imgright_array[entryindex];
// Write contents
jQuery('#entryimages').html('');
jQuery('#entryimages').html('<img class="rotate" width="132" height="138" id="bild_left" src="'+imgleft+'" /><img class="rotateright" width="154" height="162" id="bild_center" src="'+imgcenter+'" /><img class="rotate" width="132" height="138" id="bild_right" src="'+imgright+'" />');
jQuery('.person').attr('src', profileimage);
jQuery('#g_fb_name').html(blogauthor);
jQuery('#g_titel').html(blogtitle);
jQuery('#g_text').html(blogtext);
});
So I am just not using .attr('src') in the event handler....
Try to make a delay:
jQuery(document).ready(function() {
setTimeout(function () {
jQuery('.blogentry').each(function(){
// your code...
});
}, 100); // if doesn't work, try to set a higher value
});
UPDATE
Hope, this code will work.
$('.blogentry img').each(function(){
alert( $(this).attr('src') );
});
UPDATE
I'm not sure, but maybe IE can't read classes with uppercase first letter...
Try to change ".Image_center" to ".image_center"
UPDATE
Check your code again. You definitely have some error. Try this jsfiddle in IE8, attr('src') is showed correctly. http://jsfiddle.net/qzFU8/
$(document).ready(function () {
$("#imgReload").click(function () {
$('#<%=imgCaptcha.ClientID %>').removeAttr("src");
$('#<%=imgCaptcha.ClientID %>').attr("src", "Captcha.ashx");
});
});

Categories

Resources