Return ID of all iframes in a page

前端 未结 3 726
我寻月下人不归
我寻月下人不归 2021-01-18 22:38

Because of the widget format I\'m working with I have a page which has multiple iframes embedded within iframes. I won\'t paste the code as it\'s vast and unwieldy but it is

相关标签:
3条回答
  • 2021-01-18 22:56

    From the most embedded iframe:

    var ids = (function up( context, ids ){ 
       ids = ids || []; 
       // proceed if we're not at the top window yet
       if( context !== window.top){
          // point context to parent window (or top if no parent).
          context = context.parent || window.top; 
          // get the id of the first iframe in parent window; 
          // this will break if there are sibling iframes
          ids.push(context.document.getElementsByTagName('iframe')[0].id); 
    
          // recursive call to traverse parents          
          return up(context, ids); 
       } else {
          // otherwise return the list of ids
          return ids; 
       }
       }(this)); // 'this' is the initial context - current window
    
       console.log( ids );
    
    0 讨论(0)
  • 2021-01-18 23:01

    I do not believe you can reference the iframe's children directly. You will need to recursively search each iframe using it's .contents() call.

    As far as I know, this will only work as long as the same-origin policy is not violated (i.e. the iframes must point to the same domain).

    0 讨论(0)
  • 2021-01-18 23:05

    EDITED

    This returns an iframe element which has the wanted id, and null, if the wanted id is not found.

    function searchIds(wantedId) {
        var idArray = [], n,
            search = function (iframes) {
                var n;
                for (n = 0; n < iframes.length; n++) {
                    if (iframes[n].frames.length > 0) {
                        search(iframes[n].frames);
                    }
                    idArray.push(iframes[n].frameElement.id);
                    idArray.push(iframes[n].frameElement);
                }
            };
        search(window.top.frames);
        for (n = 0; n < idArray.length; n += 2) {
            if (idArray[n] === wantedId) {
                return idArray[n + 1];
            }
        }
        return null;
    }
    

    Notice, that searchIds() can't be run before onload of the main window has been fired.

    0 讨论(0)
提交回复
热议问题