How to write JavaScript for iframe and not iframe (same content) - javascript

Setup
I will be accessing content on my page sometimes from an iframe and sometimes from the same content not in an iframe.
Problem
I'm trying to figure out a way to write javascript once and include both ways of accessing that content during the declaration of the var...
so far example
var $Holder;
if($('#MyHolder iframe').contents().length > 0) {
$Holder = $('#MyHolder iframe');
}
else {
$Holder = $('#MyHolder');
}
but I can't do this since if the content is in an iframe I need to access it this way:
$Holder.contents().find('#SomeButton').on('click',function(){});
and this doesn't work if the content is directly on the page. This also does not work if I add .contents().

If I understand the question correctly, you should be able to set your $Holder to the contents() of the iframe like so:
var $Holder;
if($('#MyHolder iframe').contents().length > 0) {
$Holder = $('#MyHolder iframe').contents();
}
else {
$Holder = $('#MyHolder');
}
Then you should be able to access elements in either case like so:
$Holder.find('#SomeButton').on('click',function(){});

Related

get a dynamic id from an iframe in an iframe

I am actually doing a tricky task, I have to create pack of resource(which are pages on the website), to do so I use iframe to display the content of the pages. But I can have multiples Iframes in one Iframe.
And I want to pass some style on those iframe in iframe, so i have to target them.
I have a special node id for each pages that allow me to return only the body.
So my question is how do I get to target the id of my iframe in my iframe which I tried to do with that line var get_iframe_inside = search_inside.getElementsByTagName("iframe".id); to then modify it's style.
I know that I am not using the right way for this line, but I have been scratching my head all this morning and can't find a way.
function test(id){
var iframe = window.parent.document.getElementById(id); //select my first iframe
get_iframe_inside(id); //call my function to get the iframe in the iframe
function get_iframe_inside (id){
var search_inside = (iframe.contentDocument) ?iframe.contentDocument : iframe.contentWindow.document;
//My goal is then to modify some properties
var get_iframe_inside = search_inside.getElementsByTagName("iframe".id);
$(get_iframe_inside).css({'padding':'0px 50px', 'background-color':'#cecece'});
}
}
Well it was kind of trivial my code was nearly working i just didn't tought at how to get thoses ids.
i just had to get them by tag and after that to do an iteration with for.
var get_iframe_inside = search_inside.getElementsByTagName("iframe");
var i;
for (i = 0; i < get_iframe_inside.length; i++){
get_iframe_inside[i].style.padding='0px 50px';

Accessing certain value from iframe and using it in parent page Javascript

Inside my iframe i have a dial that spits out angle when the needle moves. Instead of getting both dial and needle both inside frame, is it possible to show the angle value somewhere else in my parent page outside the iframe. This is the code i have.
function showIframeContent(id) {
var iframe = document.getElementById(id);
try {
var doc = (iframe.contentDocument)? window.frames[clkwise1].document.getElementId("demo").value;
alert(doc.body.innerHTML);
}
catch(e) {
alert(e.message);
}
return false;
}
The standard and cross-browser way to access the content of an iframe is:
iframe.contentWindow.document
I would expect this to work in your case:
document.getElementById("clkwise1").contentWindow.document.getElementById("demo").value
(I'd need to see the page itself to confirm it - for example I assume "demo" is an input element. Also, note your typo in getElementById)
Live demo: http://jsfiddle.net/ZWC6v/

How to disable div blocks having a certain id pattern?

I would like to write a greasemonkey script to disable a div on a certain page.
On any given load of the page I don't know where in the DOM the div will be but I know it's always called <div id = "alertPanel"> ....</div>
How would I go about disabling this div?
My intial thoughts were something along the lines of:
var myDivs= document.getElementsByTagName('div');
for (i=0; i<myDivs.length; i++)
{
if (myDivs[i].<get id property somehow> = "alertPanel")
myDivs[i].style.visibility = 'hidden';
}
but as you can tell I'm stuck at accessing the id property for an equality check.
Incidently, I'm using a text editor to write this - I guessing that a standard javascript editor would give an autocompletion list after typing in myDivs[i].
If it has an id, you can use document.getElementById:
var div = document.getElementById("alertPanel");
Then if it exists, you can either remove it (probably a bad idea) or hide it:
if (div) {
div.style.display = "none"; // Hides it
// Or
// div.parentNode.removeChild(div); // Removes it entirely
}
Update: Re your comment on another answer:
thanks for your answer. Does your statemt apply to a page with iframes too. The div in question is in an iframe. I've tried ypur solution and it didn't work unfortunately. maybe a link to the page will help: tennis.betfair.com the div i want to disable is the one with id: minigamesContainer
If the element is in an iframe, then you have to call getElementById on the document that's in the iframe, since iframes are separate windows and have separate documents. If you know the id of the iframe, you can use document.getElementById to get the iframe instance, and then use contentDocument to access its document, and then use getElementById on that to get the "minigamesContainer" element:
var iframe, div;
iframe = document.getElementById("the_iframe_id");
if (iframe) {
try {
div = iframe.contentDocument.getElementById("minigamesContainer");
if (div) {
div.style.display = "none";
}
}
catch (e) {
}
}
(The try/catch is there because of a potential security error accessing the content of the iframe; I don't know Greasemonkey well enough to know whether the SOP applies to it. I tend to assume it doesn't, but better safe...)
If you don't know the id of the iframe or if it doesn't have one, you can just loop through all of them by getting them with document.getElementsByTagName and then looping:
var iframes, index, iframe, div;
iframes = document.getElementsByTagName("iframe");
for (index = 0; index < iframes.length; ++index) {
iframe = iframes[index];
try {
div = iframe.contentDocument.getElementById("minigamesContainer");
if (div) {
div.style.display = "none";
break;
}
}
catch (e) {
}
}
References:
DOM2 Core
DOM2 HTML
DOM3 Core
HTML5 Web Applications APIs
In valid HTML you can have only element with certain ID. So:
document.getElementById('alertPanel').style.visiblity = 'hidden';
But if you still need to iterate all div's and check their ID's, then this should work:
if (myDivs[i].id == "alertPanel") myDivs[i].style.visibility = 'hidden';

append element in head of an iframe using jquery

i want to append a style sheet(css) link to the head of an iframe using jquery .
i tried with the following code but not working.
$('#tabsFrame').contents().find("head").append(cssLink);
i am used to append data to an iframe by using this line of code
$('body', window.frames[target].document).append(data);
In your case, this line would look like this
$('head', window.frames['tabsFrame'].document).append(cssLink);
EDIT:
Add <head></head> to the iframe and change your var cssLink to
cssLink = '<link href="cupertino_1.4/css/cupertino/jquery-ui-1.8.7.custom.css" type="text/css" rel="Stylesheet" class="ui-theme" />
well, you can check with this:
$('#tabsFrame').contents().find("head")[0].appendChild(cssLink);
I believe you can't manipulate the content of an iframe because of security.
Having you be able to do such a thing would make cross-site-scripting too easy.
The iframe is totally seperate from the DOM of your page.
Also, java and javascript are two completely different things!
Follow the Link to see the difference here
This could be related to IE not allowing you to add elements in the DOM, check out the clever solution here
EDIT:
Thanks #kris, good advice to add more info in case links break:
Here is the main code snippet from the link, in case it goes out again.
(This is only needed with some IE version, for the most part, the other answer work just fine)
var ifrm;
//attempts to retrieve the IFrame document
function addElementToFrame(newStyle) {
if (typeof ifrm == "undefined") {
ifrm = document.getElementById('previewFrame');
if (ifrm.contentWindow) {
ifrm = ifrm.contentWindow;
} else {
if (ifrm.contentDocument.document) {
ifrm = ifrm.contentDocument.document;
} else {
ifrm = ifrm.contentDocument;
}
}
}
//Now that we have the document, look for an existing style tag
var tag = ifrm.document.getElementById("tempTag");
//if you need to replace the existing tag, we first need to remove it
if (typeof tag != "undefined" || tag != null) {
$("#tempTag", ifrm.document).remove();
}
//add a new style tag
$("HEAD", ifrm.document).append("");
}

Can javascript running inside an iframe affect the main page?

Partial Code:
My below code pulls a query from my DB and then uses inner.HTML = to display the data inside a div. It works fine in it original use....
However the below version is called inside a iFrame as it is used to update the page.
The page has no errors and the JavaScript fires however the last line does not work...
I have just realized that perhaps since it is loading in the hidden iFrame it is trying to set the innerHTML of a div inside the iFrame and that of course will not work.
Is this what is happening? It doesn't make sense because I have another script that calls JavaScript at the end of it in the same manner and it works fine.
<?php
while ($row = mysql_fetch_array($result))
{
$p = $p.'<div id="left"><img src="http://www.sharingizcaring.com/bleepV2/images/thumbs/'.$row[image].'" /></div>';
$p = $p.'<div id="right"><h2>'.$row[artist].' - '.$row['title'].'</h2><br>'.$row['message'].'<br>';
$p = $p.''.$row[username].' '.$row[date].'</div>';
$p = $p.'<div style="clear: both;"></div>';
$p = $p.'<div id="dotted-line"></div>';
}
$p = addslashes($p);
?>
<script>
alert('posts are firing? ');
document.getElementById('posts').innerHTML = 'why doth this faileth?';
</script>
You can do it! Read here for more info
You can affect the document with contains the iframe by setting and getting variables from the window element:
// normally you use...
var whatever = "value";
// use the window object instead, which is shared
// between the iframe and the parent
window.whatever = "value";
The other thing you should know is that you can access the main document via the parent object
inside the iframe you can use...
parent.someattr;
// or try this
parent.getElementById('some_element');
I think what you want is:
parent.getElementById('posts').innerHTML = 'why doth this faileth?';
The part in the iframe isn't considered the same document.
you have to use parent.

Categories