View Full Version : Detect IFRAME Source

01-09-2006, 02:53 PM
Hi Guys

Need your help with a script pls:

Basically I have an html with 3 links (ie. 1.htm ,2.htm &3.htm) that are targeting an embedded IFRAME.

When the user clicks on 2 for example, 2.htm will appear in the Iframe. What I need is for a script to detect (in Realtime without refreshing the page) which file is within the src of the Iframe and then call the appropriate function [ie. if iframe.src = 2.htm then function 2(); will be called or if its 1.htm then function 1() will be called]

I've tried the .watch command but without success. :confused:

Your help will be much appreciated!


01-10-2006, 07:35 AM
I'd never heard of the .watch command or method but, lo and behold, it exists. It's support seems limited (read non-existent) in IE and its usefulness restricted to script created properties (not attributes, like src) of objects in FF but, I am open to learning more about it and being proved wrong on this. Be that as it may, your goal seems not to require .watch. The most straightforward method would be to have onclick events for your links which activate the functions in question when each in turn is clicked. This will miss src changes accomplished via the use of the back and forward buttons though. To make matters a bit more complex, an iframe's src attribute doesn't change when a link is clicked that targets the iframe with a new page. You have to use script to change the src. A link will change the location.href though, as will the back and forward buttons, as will actually changing its src via script. So it is the location.href we should test for and this requires that the iframe be accessed via its name:

<iframe name="fred" src="1.htm" frameborder="0"></iframe>
<script type="text/javascript">
var flag=0
function watchFrame(){
if (flag!==1&&fred.location.href.indexOf('1.htm')!==-1){
else if (flag!==2&&fred.location.href.indexOf('2.htm')!==-1){
else if (flag!==3&&fred.location.href.indexOf('3.htm')!==-1){
setInterval("watchFrame();", 400)

Notes: This assumes that there will never be a page like '11.htm' loaded into the iframe, as the test for '1.htm' will see that as a 'yes'. In fact this setup assumes that things will be as described in your post, with only '1.htm' '2.htm' and '3.htm' ever loaded into the iframe. Other pages with similar names could throw things off. The use of the flag is to assure that the spawned function fires only once per page change.

01-10-2006, 10:13 AM
It works :)

Thanks Jon!