[英]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: HTML:
<div id="AllowToBeEmbedded"> <b>Hello there!</b> </div> <div class="nonsense"> <b>Leave me out of this</b> </div>
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.您可以检查页面是否在 iframe 中呈现,如果是这种情况,请隐藏/删除您不想显示的页面部分。
Typical way to check if the page is in iframe mode is by comparing current window
object to a window.top
reference:检查页面是否处于 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'
}
}
To avoid possible content flashing until it's removed it also would make sense to hide it additionally with CSS.为了避免可能的内容在被删除之前闪烁,使用 CSS 额外隐藏它也是有意义的。 For this I would have this helper code in the very beginning of the page (in
<head>
):为此,我将在页面的最开头(在
<head>
)使用此帮助程序代码:
<script>
const isInIframe = window.top !== window
if (isInIframe) {
document.documentElement.classList.add('iframe')
}
</script>
<style>
html.iframe .nonsense {
display: none;
}
</style>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.