如何允许我的部分页面在其他网站上用作iframe?

时间:2018-02-18 10:10:42

标签: javascript html css html5 http

如何允许我的网站的一部分嵌入其他网站?

HTML:



<div id="AllowToBeEmbedded">
  <b>Hello there!</b>
</div>

<div class="nonsense">
  <b>Leave me out of this</b>
</div>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

您可以检查网页是否在iframe中呈现,如果是这种情况,则隐藏/删除您不希望显示的网页部分。

检查网页是否处于iframe模式的典型方法是将当前window对象与window.top引用进行比较:

if (window.top !== window) {
  // we are within an iframe. hide parts of the page
  hideForIframe()
}

function hideForIframe() {
  const toHide = document.querySelectorAll('.nonsense')
  for (let i = 0; i < toHide.length; i++) {
    toHide[i].parentNode.removeChild(toHide[i])
    // or hide toHide.style.display = 'none'
  } 
}

为了避免可能的内容闪烁,直到它被删除它也是有意义的另外用CSS隐藏它。为此,我将在页面的最开头(<head>)中有这个帮助代码:

<script>
  const isInIframe = window.top !== window
  if (isInIframe) {
    document.documentElement.classList.add('iframe')
  }
</script>
<style>
  html.iframe .nonsense {
    display: none;
  }
</style>
相关问题