select and refresh an iframe not knowing the id or name - javascript

is there a way to select and refresh an iframe, not knowing his id or name, and also doing it from inside the same iframe?
the problem is that knowing if the iframe needs to be refreshed is on a response from the server on the iframe.
so, how can i force a refresh on this iframe?
i have found ays to refresh an iframe but all of them require the id like:
document.getElementById('iframeid').src = document.getElementById('iframeid').src
or
document.getElementById('some_frame_id').contentWindow.location.reload();
also there are more than 1 iframe on the web page and they are loaded dinamicaly into a jquery tab.
i can use jquery or js

if several iframes are in the same container, and you don't know in which order they are loaded, then I don't think you can target one of them.
If there's only one per container and you know the container's id, then you can do
jQuery('iframe','#container').attr('src',url);

How do you select a single iframe element without knowing any of its identity.
The only information probably is the tagName.
To refresh iframe elements, try this:
Array.prototype.slice.call(document.querySelectorAll('iframe')).forEach(function(element){
element.src = element.src;
})
Change the selectors query as you like.

Try this
Create this function in parent window/page in which iframe will be loaded.
function reload(){
var elems = document.getElementsByTagName("iframe");
for (var i = 0; i < elems.length; i++) {
elems[i].src = elems[i].src;
}
}
Call parent.reload() from iframe to reload itself.
But this script will reload every iframe in the page because no specific id or name is available in your case.
if it is available then use,
function reload(){
var elems = document.getElementsById("iframe_id");
elems.src = elems.src;
}

Related

Resetting CSS properties in bookmarklet

I'm trying to attach new <div> element with some content via bookmarklet and add some inline CSS.
The problem is that the CSS from the main page usually affects this div too.
What would be preferred approach to ensure that my styles from bookmarklet are always more important that the ones from any parent page?
The most trustworthy solution would be to set all possible CSS properties for each element inside the div. Is this wise? Where can I get the list?
I've found cleanstate.css which may do the reset.
Maybe some js solution would work better? Eg. detect which styles has been aplied by the main page, and reset them to default values? I'll have jQuery available in this bookmarklet anyways.
The reliable solution would be iframe.
You can create it dynamically and assign content using 'javascript:' protocol in src tag.
var iframe = document.createElement('iframe');
iframe.src = "javascript:'<div> Yours Content </div>'";
document.body.appendChild(iframe);
Or you can insert empty iframe, wait it to be loaded and modify iframe document as required. For example:
var iframe = document.createElement('iframe');
iframe.src = 'about:blank';
document.body.appendChild( iframe );
iframe.onload = function() {
iframe.contentWindow.document.body.innerHTML = '<div> Yours content </div>';
};
Alternatively, you can create separate .html page and insert it as iframe. <iframe src="http://example.com">Although, you will need to host page somewhere and document won't be able to access parent page without additional scripting. ( .postMessage() )

How can I detect if an iFrame gets redirected to another url?

I want to list an iframe with a classified ad in it. Sometimes the vendors redirect the page to their homepage when the item is no longer available. I want to be able to identify this so I can de-index the item assuming it has sold. What is the best method to accomplish this?
You can use jQuery's load function that fires onload or reload.
http://api.jquery.com/load/
You will need to store the number of times the iframe has reloaded.
Something like,
var reloaded = 0;
$("#iframe_id").load(function(){
reloaded++;
});
You can not detect the location of the iframe when it is in a different domain unless they have the proper headers set for CORS.
The only way to do it without worrying about the other domain is to have your serverside code run a check on the page and see if it redirects.
On the frame load, detect what the URL is:
var frameLoadCount = 0;
var firstURL;
$('iframe').load(function() {
if (frameLoadCount === 0) {
firstURL = $(this).attr('src');
} else {
if (firstURL !== $(this).attr('src')) {
// The iframe has been redirected.
}
}
});
Basically the above code runs everytime the iframe has loaded, checks if it's the first time, if it is, assign the URL to a variable. If it has loaded more than once, check if the original url matches the current url.
This has benefits from just checking if it's loaded more than once, because you can target specific sources etc.

Click event in iframe

I'm trying to append the url of the parent page an iframe is located in based on the current url within the iframe.
This is all taking place on the same domain, so I don't think there should be any security issues.
EDIT:
My code now looks like the following:
function locator_url() {
var iframeUrl = alert(document.getElementById("dealer- locator").documentWindow.location.href);
var iframeUrlSplit = iframeUrl.split('/locator/');
window.location.hash = '#' + iframeUrlSplit[1];
};
$(document).ready(function(){
document.getElementById("dealer-locator").contentWindow.onload = locator_url();
});
Now the default src for the iframe is http://localhost/meade/locator/
The page the iframe is on is http://localhost/meade/dealerlocator/
The code works for the initial page load, the parent url is appended to localhost/meade/dealerlocator/#
However, when I click a link inside the iframe the parent url doesn't change, even though the href value in the iframe has.
The parent url should have it's hash updated to something like:
localhost/meade/dealerlocator/#results_list.php?showonly=US&tab=US&zip=&distance=10&state=&city=&name=
But that's not happening.
What am I missing?
Did you try:
document.getElementById("dealer-locator").contentWindow.onload = locator_url;
Well, if you need click events in your iframe, then you could do it this way:
Car.com
Then locator_url() gets called in the parent page. Same goes for using load events (I mean, load events that occur in the iframe context).

How do I remove an iframe from within itself (that has been dynamically created and loaded with src)

I want to be able to remove an iframe from within itself. The iframe is created dynamically and the content is loaded with 'src'.
I create my iframe like this:
var i = document.createElement('iframe');
i.id = 'proxy_frame';
i.name = 'proxy_frame';
i.setAttribute('src', url);
document.body.appendChild(i);
Then from within 'url' I want to be able to remove/close the iframe.
Before loading the data into the iframe with src I used document.write:
window.frames['proxy_frame'].document.write(html);
and then I was abloe to remove the iframe with:
window.parent.document.getElementById("proxy_frame").parentNode.removeChild(window.parent.document.getElementById("proxy_frame"));
But this does not work with 'src'.
Note: This is for a bookmarklet so I don't want to use jQuery or another library.
Define a method in your parent page
function removeElement() {
var d = document.getElementById('body'); // or any other parent element
var proxy_frame = document.getElementById('proxy_frame');
d.removeChild(proxy_frame);
}
To call this method from your iframe simply use this
Remove me
For local domain iframes you don't need to rely on ids.
window.parent.document.body.removeChild(window.frameElement);
window.frameElement has reasonable support https://developer.mozilla.org/en-US/docs/Web/API/Window/frameElement
You can't access the parent page as long as it's in a different domain.
Set up a page in your site that can be used to remove the iframe, then in the iframe you just go to that page.

Telling when an iframe is on a new URL

I am using JavaScript to make a small iframe application, and I cannot seem to figure out a way to update the URL in my URL bar I made when someone clicks a link inside the iframe.
It needs to be instantaneous, and preferably without checking every millisecond whether or not the value of document.getElementById('idofiframe').src has changed.
I can't seem to find a simple property to tell when the url has changed, so if there is not one, then solving this programmatically will work as well.
Thanks for the help!
This will be difficult to do because it is considered xss and most browsers block that.
There are most likely some workarounds involving AJAX.
First of all, what you want to do will be possible only if the source of your iframe points to the same domain as the parent window. So if you have a page page.html that iframes another page iframed.html, then both of them have to reside on the same domain (e.g. www.example.com/page.html and www.example.com/iframed.html)
If that is the case, you can do the following in the iframed.html page:
<script type="text/javascript">
window.onload = function() {
var links = document.getElementsByTagName('a');
for (var i=0, link; link = links[i]; i++) {
link.onclick = function() {
window.parent.location.href = '#' + encodeURIComponent(this.href);
}
}
}
</script>
This will make it so that whenever you click on a link in iframed.html, the url bar will put the url of the link in the "hash tag" of the url (e.g. www.example.com/page.html#http%3A%2F%2Fwww.example.com%2FanotherPage.html)
Obviously, you would have to have a script like this on every page that is to appear inside the iframe.
Once this is in place, then you can put this snippet inside of page.html, and it will make the iframe automatically load the url in the hash tag:
window.onload = function() {
var url = window.location.hash.substr(1);
if (url) {
document.getElementById('iframe').src = url;
}
}
I unfortunately haven't run this code to test it, but it is pretty straight forward and should explain the idea. Let me know how it goes!
You could add an onload event to the iframe and then monitor that - it'll get thrown whenever the frame finishes loading (though, of course, it could be the same URL again...)
Instead, can you add code to the frame's contents to have it raise an event to the container frame?
In IE, the "OnReadyStateChanged" event might give you what you want.

Categories