tags:

views:

27

answers:

2

Hello,

I have a number of iframes calling a function in my main page. Is there a way to find out the ID of the iframe which called the function?

There are all part of same domain so that should not be an issue.

Thank you for your time.

A: 

I'd say you need to send an identifier along with your method calls. It can be an optional parameter that does no harm if not present, like:

function foo(value, refId) {
  // do stuff with value
  if (typeof refId!=='undefined') {
    // handle this
  }
}
npup
I can't do that unfortunately.
Alec Smart
How so? The refId can be anything (need not be exactly the DOM id of your iframe), just as long as you can use it to resolve the caller somehow. But now it sounds like you have no control over the calls from the frame?
npup
I have control over the iframe content, but not the iframe id or the iframe location
Alec Smart
A: 

The most common way is to have the control pass itself to the function

<script>function doClick(e){ alert('id = ' + e.id); }</script>
<span id=test onclick="doClick(this)"> click here</span>

Another way would be by using the:

event.srcElement

As documented here.

A third way but not as reliable would be by using:

document.activeElement.name

The latter is not the best approach.

In my personal opinion I'd go with the first one, as it will work 100% of the time, and won't give you browser issues.

UPDATE To get the current iframe's id (assuming you don't have nested iframes on the same page), you can simply use:

this.document.getElementsByTagName('body')[0]​.id

And then simply pass it along with the call to your function. just make sure the body has the same ID as your iframe for example.

Let me know if it helps you.

Marcos Placona
But how do I get to know the iframe's ID. These IDs are randomly generated.
Alec Smart
Simply pass it with the function call. you could use something like: parent.frames[0].id
Marcos Placona
Since different iframes will have different IDs, it wont always be parent.frames[0].id. It could be parent.frames[1].id etc.
Alec Smart
Updated the answer with some more ways
Marcos Placona
sorry, this is not what i was looking for. but i am marking this as correct for the time being.
Alec Smart