检查iframe页面是否包含使用JavaScript或jQuery的内容

Check if iframe page has content using JavaScript or jQuery

本文关键字:jQuery JavaScript iframe 是否 包含使 检查      更新时间:2023-09-26

我正在动态创建一个iframe标记,它从页面中提取内容,在显示之前如何检查我从中提取的页面是否有内容?在生成iframe标记之前,我应该先检查内容吗?

如何检查iframe页面是否为"<html><body></body></html>",因此不显示"adContainer"?

以下是我迄今为止编写的一些代码。。。

function setAttributes(el, attrs) {
  for(var key in attrs) {
    el.setAttribute(key, attrs[key]);
  }
}
// set ad iframe
function setAdiFrame(iWidth, iHeight, bookname) {
  var randNum = Math.floor(Math.random()*1000000000);
  var adFrame = document.createElement('IFRAME');
  setAttributes(adFrame, {
    "src": "http://www.foo.com/" + bookname + "/;cat=" + bookname + ";sz=" + iWidth + "x" + iHeight + ";ord=" + randNum,
    "height": iHeight,
    "width": iWidth,
    "border": "0",
    "scrolling": "no",
    "allowtransparency": "true"
  });
  $('.ad').append(adFrame);
}
// ad container
var adContainer = $('.ad-container');
// check if ad container exist
if(adContainer.length > 0) {
  // check if it's mobile
  if(categorizr.isMobile) {
    setAdiFrame(300, 400, 'bookname');
  // otherwise, show desktop ad
  } else {
    setAdiFrame(728, 660, 'bookname');
  }
  // show ad once iframe page is loaded
  adContainer.find('iframe').on('load', function() {
    adContainer.css('display', 'block');
  });
}

adContainer的输出标记就是这样。

<div class="ad-container" style="display: block;">
    <div class="ad">
        <a id="close" href="button:close"></a>
            <iframe src="http://www.foo.com;bookname/;cat=bookname;sz=728x660;ord=849890967" height="660" width="728" border="0" scrolling="no" allowtransparency="true"></iframe>
    </div>
</div>

IFrame页面src中输出的html可以是"<html><head></head><body></body></html>"。如果是这样的话,我不想显示adContainer。

if(adFrame.contents().find("body").html()=="") {
    adContainer.css('display', 'none');
}