1

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>
Niveditha Karmegam
  • 742
  • 11
  • 28
ipid
  • 253
  • 1
  • 4
  • 16
  • Not possible. You can use an external JavaScript that creates or extracts that part and they can embed that – mplungjan Feb 18 '18 at 10:11
  • @mplungjan I see, how can I do that with external JavaScript? – ipid Feb 18 '18 at 10:16
  • detect if the page is used as iframe, if yes remove the non needed part https://stackoverflow.com/questions/925039/detect-iframe-embedding-in-javascript – Temani Afif Feb 18 '18 at 10:17
  • @TemaniAfif - that will still send the other part. If that is acceptable then yes – mplungjan Feb 18 '18 at 10:23
  • @mplungjan yes sure, but if we need to visually hide the non-needed part i guess it should be ok ... but if we want to avoid sending those part it would be impossible as i don't think the server will be able to make a difference between a normal call and iframe call. – Temani Afif Feb 18 '18 at 10:25
  • From a server you could ask for a parameter in the request and not send the rest if present. In JS, you can use Dom manipulation in the script that will show data on your site and theirs. Additionally they could embed that without an iframe – mplungjan Feb 18 '18 at 10:25
  • Actually it's quite possible with just some minimal javascript, not even external. – dfsq Feb 18 '18 at 10:53

1 Answers1

1

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>
dfsq
  • 191,768
  • 25
  • 236
  • 258