使用jQuery动态检测iframe?

时间:2015-06-02 14:14:33

标签: javascript jquery iframe

为了检查iFrame当前是否已打开,您可以使用:

if (window!=window.top) { /* I'm in a frame! */ }

但是如果我想在iFrame打开时收到警报怎么办?如何让JS自动检测iFrame已在当前页面上打开或插入到DOM中?

3 个答案:

答案 0 :(得分:4)

使用JQuery,您可以使用以下代码:



$('body').on('DOMNodeInserted', 'iframe', function(e) {
  console.log("Iframe inserted into document");
});

// To test it
$('button').click(function() {
  $('body').append('<iframe></iframe>')
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Add iframe</button>
<hr />
&#13;
&#13;
&#13;

答案 1 :(得分:3)

与Nick相同的解决方案,没有jQuery,使用(现已弃用)MutationEvents

&#13;
&#13;
document.body.addEventListener('DOMNodeInserted', function(e) {
  if (e.target.tagName == 'IFRAME') {
      console.log("Iframe inserted into document", e);
  }
});

document.querySelector('button').addEventListener('click', function() {
  document.body.appendChild(document.createElement('iframe'))
});
&#13;
<button>Add Iframe</button> <hr />
&#13;
&#13;
&#13;

由于不推荐使用MutationEvents,您可能需要使用MutationObservers,请注意它们确实需要IE 11。

&#13;
&#13;
document.querySelector('button').addEventListener('click', function() {
  document.body.appendChild(document.createElement('iframe'));
  document.body.appendChild(document.createElement('iframe'))
});
  
// create an observer instance
var observer = new MutationObserver(function(mutations) {
  mutations.forEach(function(mutation) {
   for (var i = 0; i < mutation.addedNodes.length; i++) {
     if (mutation.addedNodes[i].tagName == 'IFRAME') {
       console.log('Added IFrame', mutation.addedNodes[i]);
     }
   }
  });    
});
 
// pass in the target node, as well as the observer options
observer.observe(document.body, {
  attributes: false,
  childList: true,
  characterData: false
});
 
&#13;
<button>Add Iframe</button> <hr />
&#13;
&#13;
&#13;

答案 2 :(得分:1)

不推荐使用DOMNodeInserted事件。您应该使用MutationObserver代替:

&#13;
&#13;
new MutationObserver(function (mutations) {
  var observer = this;
  mutations.forEach(function (mutation) {
    [].forEach.call(mutation.addedNodes, function (node) {
      if (node.nodeName === 'IFRAME') {
        alert('An iframe was inserted!');
        // if you are only interested in the first inserted iframe:
        observer.disconnect();
      }
    });
  });    
}).observe(document.body, {
  childList: true,
  subtree: false // true to "observe" the whole page
});
&#13;
<button type="button" onclick="document.body.appendChild(document.createElement('iframe'))">add iframe</button>
&#13;
&#13;
&#13;

MutationObservers未在某些传统浏览器(如IE 10)中实现。要么告诉IE用户将他们的东西放在一起并切换到Firefox,Chrome或 Opera Vivaldi或功能测试浏览器:

try {
    /...my code.../
} catch (e) {
    try {
        /... Nick Hermans' code.../
    } catch (e) {
        alert('Update your browser already!');
    }
}