ipid
ipid

Reputation: 253

How to allow a part of my page be used as iframe on other site?

How can I allow a part of my website be embedded on other site?

HTML:

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

<div class="nonsense">
  <b>Leave me out of this</b>
</div>

Upvotes: 1

Views: 246

Answers (1)

dfsq
dfsq

Reputation: 193251

You could check if the page is rendered within an iframe or not, and if this is the case hide/remove parts of the page you don't want to be displayed.

Typical way to check if the page is in iframe mode is by comparing current window object to a window.top reference:

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'
  } 
}

To avoid possible content flashing until it's removed it also would make sense to hide it additionally with CSS. For this I would have this helper code in the very beginning of the page (in <head>):

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

Upvotes: 1

Related Questions