I need to know when a specific iframe is created on a page.
The iframe is created with JS when the user presses a button, and can be created and destroyed many times.
UPDATED: The JS that creates the iframe is part of the original page so I cannot modify it or access its variables or functions, chrome extensions are sandboxed.
I don't have control over the contents of the iframe and cannot inject any JS in it.
I can only inject JS in the main page but have no other control on it otherwise.
(it's for a chrome extension and as far as I know it's only possible to inject JS code in the main page or iframes loaded with the page but not iframes created dynamically after the page has loaded)
For the moment I do this:
window.setInterval( function() {
$("iframe").each(function(){
if ($(this).attr('id')) {
if ($(this).attr('id') == "iframe_id") {
//my code
}
}
});
}, 1000);
but I would really like to avoid the setInterval because of performance issues.
Would this be possible at all somehow?
A. Wolff probably answered your question already ("The iframe is created with JS when the user presses a button" So you know when the iframe is created").
If you're still not sure what to do... well:
The interval is not a good idea - but you probably figured that out yourself. Try the on() method. That should help.
$( "iframe" ).on( "click", function() {
alert( "This is my iframe!" );
});
If you are having trouble selecting the content of the iframe, maybe you should try accessing elements like this:
$( "#iframe-id" ).contents().find( ".what-i-am-looking-for" ).hide();
The jQuery documentation will be extremely helpful if that is what you are looking for:
http://api.jquery.com/on/
http://api.jquery.com/contents/
Cheers!
Related
Imagine the situation, where I have an iframe of a website.
Inside that website there is a button in which I want to click via javascript.
After looking into the HTML of the website, I noticed that the button is actually a div, with class like.
So I tried this:
function likeFunction()
{
var iframe = document.getElementById("myFrame");
var elmnt = iframe.contentWindow.document.getElementsByTagName("div")[10];
elmnt.click();
}
or
function likeFunction()
{
var iframe = document.getElementById("myFrame");
iframe.contentWindow.document.getElementsByTagName("div")[10].click();
}
and my final attempt was giving that div an ID='ex'
function likeFunction()
{
var iframe = document.getElementById("myFrame");
iframe.contentWindow.document.getElementById("ex").click();
}
But in the end, nothing really did it for me, any ideas?
Thanks in advance!
Your solution should work, as long as the iFrame is on the same domain. If it is not, you should get an error on this line
iframe.contentWindow.document.getElementsByTagName("div")[10].click();
So you would probably have noticed.
My only thoughts are:
you might be using the wrong selector,
you might be running the posted script on the iframe itself, not on the parent scope
you might be running this before the iFrame is loaded. Maybe running this onDocumentComplete on the parent document or some other way.
The click listener might be on on different element than the one you are progamatically clicking on.
But in the scenarios I mentioned, you should be getting an error, which you didn't mention.
Otherwise, the general approach works on my tests.
Firstly both the parent page and the iframe are hosted on the same server (my localhost on WAMP) so same origin policy should not be an issue here.
I can't get the trigger to work. My iframe has the id of iframe.
$(window).load(function(){
//iframe ad hovers
$('#iframe').contents().find('body div').click(function(){
alert('do something here');
});
});
what am i doing wrong?
I'm not sure the browser's going to propagate a "click" event from the window context of the <iframe> out to the containing window. Does the document loaded into the <iframe> have its own copy of jQuery? If so, you can try this:
$('#iframe').contents().$.find('body div').click(function(){
alert('do something here);
});
That change makes the jQuery code in the <iframe> window handle the event.
Well I think that #jAndy is right and that should work as is - but you have to make sure the document in the frame is loaded. Try this:
$('#iframe').load(function() {
$(this).contents().find('body div').click(function() { alert("hi"); });
});
Your code is not wrong; i think the only mistake you are doing is that you are asking for the iframe's content on the parent page load which means at this stage the iframe has not been loaded yet.
Try my quick example http://jsfiddle.net/UFM44/4/
It is same as your code but i trigger it after clicking on "now" link. if you then click on the logo you can see the alert() message.
I have numerous iframes that load specific content on my pages. Both the parent and iframe are on the same domain.
I have a scrollbar inside the iframe that doesn't seem to load correctly in all browsers. But when I refresh the iframe it loads perfect. I have no idea why it does this.
I have used the meta refresh, which works but I don't want the page to refresh constantly, just once.
The solution I'm looking for will reload the iFrame content after the iFrame is opened, with a minimal delay.
Edit
I realized that my page loads all of my iframes when the index is loaded. The iframes appear in a jQuery overlay, which is also loaded but visibility:hidden until called. So on this call is when I would want the iframe to be reloaded.
Could anyone help me come up with a Javascript function that reloads the iFrame when I click the link to the iFrame? I've gotten close but I know nothing about js and I keep falling short. I have a function that reloads the page, but I can't figure out how to get it called just once.
I have this so far:
<script type="text/javascript">
var pl;
var change;
pl=1;
function ifr() {
if (pl=1) {
document.location.reload([true]);
alert("Page Reloaded!");
change=1;
return change;
}
change+pl;
}
So basically it uses the document.location.reload which works to reload the page. I'm trying to then make pl change to something other than 1 so the function doesnt run again. I've been calling this JS from the body with onLoad.
All the leads on this went dead, but I did find a code snippet that worked. Not written by me, and I don't remember where it came from. Just posting to help someone should they ever have the same question.
<div class="overlay-content"> //Content container needed for CSS Styling
<div id="Reloader">
//iFrame will be reloaded into this div
</div>
//Script to reload the iframe when the page loads
<script>
function aboutReload() {
$("#Reloader").html('<iframe id="Reloader" height="355px" width="830px" scrolling="no" frameborder="0" src="about.html"></iframe>');
}
</script>
</div>
Basically just loads the iFrame source when the window with the iFrame opens, as opposed to the iFrame loading when the original page loads.
Beyond the scope of the original question, however this jQuery snippit works with cross domain iframe elements where the contentDocument.location.reload(true) method won't due to sandboxing.
//assumes 'this' is the iframe you want to reload.
$(this).replaceWith($(this).clone()); //Force a reload
Basically it replaces the whole iframe element with a copy of itself. We're using it to force resize embedded 3rd party "dumb" widgets like video players that don't notice when their size changes.
On the iframe element itself, set an onload:
iframe.onload = function() {this.contentWindow.location.reload(); this.onload = null;};
(Only works if the iframe's location is in the same domain as the main page)
Here's a complete solution to the original question:
<iframe onload="reloadOnce(this)" src="test2.html"></iframe>
<script>
var iframeLoadCount = 0;
function reloadOnce(iframe) {
iframeLoadCount ++;
if (iframeLoadCount <= 1) {
iframe.contentWindow.location.reload();
console.log("reload()");
}
}
</script>
The updated question is not really clear (what's "the link to the iFrame" and where is it in your snippet?), but you have a few issues with the code:
"calling this JS from the body with onLoad", assuming you mean an iframe's body, means the variable you're hoping to use to avoid infinite reloading will get clobbered along with the rest of the iframe's page when it's reloaded. You need to either load a slightly different URL in the iframe (and check the URL on iframe's onload before reloading) or put the flag variable in the outer page (and access it with parent.variableName - that should work I think)
if (pl=1) { should use ==, as = is always an assignment.
change+pl; has no effect.
I spent hours trying to debug a jquery mobile page I had created and finally got it to work. I had put the script it in the data-role="page" class="page-map4" div. I was wondering why this was the case, I would rather this not be magic to me. This didn't matter if I accessed the page directly, only if I had accessed it from another JQuery Mobile page.
$('.page-map4').live("pageshow", function(){
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(success, error);
} else {
error('Geolocation not supported');
}
});
Question: Why does the above script have to be in the page data-role div to work correctly when navigated from another JQuery Mobile page?
For page events I simply do this in my jQuery code. This goes in a <script> tag-set in the <head> element of a page, after any document binding to the $.mobile global:
$('#YOUR_PAGE_ID').live('pageshow',function(event, ui){
yourGeoCode();
});
You should use the pageinit event see this post 'Using jQuery Mobile – Remember to use pageinit() and not $(document).ready()' for more information
Howdy guys, im having trouble finding help on creating a callback in certain situations.
I have a piece of code which loads a links page in to an iframe and then changes the scr if another link is pressed.
$(".iframe").hide();
$(".lnk").click(function(){
$(".iframe").show('slow')
;})
;
$(".frmclose").click(function(){
$(".iframe").hide('slow')
;})
;
The above runs within (document).ready
below is outside of this (for some reason it does not work on the inside)
function changeIframeSrc(id, url) {
if (!document.getElementById) return;
var el = document.getElementById(id);
if (el && el.src) {el.src = url;return false;}return true;}
the link :
google
prior to this i have the div in which the iframe is in become unhidden. I also have a button within that div which hides the div + iframe.
What im having problems with is once the iframe has been opened and then closed via the div link if it is re-opened by clicking a different link the iframe unhides to display the old page then changes. But what i want is for the frame to load the new page(while hidden) then unhide to display it. I thought of using a callback after the iframe src change but i cant see where i would implement it.
Example of it happening
(click the GDPH button to see the links for the iframe)
Any thoughts or help appreciated.
Regards
B Stoner
I think that all you need to do is clear the src of the <iframe> when it is closed. That will clear the page so that next time you show the iFrame it will start out blank again.
I made a small demo of this functionality that uses the 3 links from your page as an example. The <iframe> starts hidden (by CSS) and each link will show the <iframe> and then load the remote site. I added a close iframe link to simulate the close link you have under the <iframe> on your site.
Hope this helps!
Edit: Updated the demo link to include the callback part. Somehow missed that when I read the question!
Edit 2: Your changeIframeSrc function was not working was because it was defined inside the jQuery anonymous function and is a closure. See calling Jquery function from javascript
I would catch the .load() event for the iframe, this will fire after the document has been loaded in to the iframe.
$(".iframe").load(function { /* code to run when iframe is loaded */ });