Joyber 发布的文章

内容转自:https://liaoxuefeng.com/blogs/all/2024-02-25-auto-resize-iframe/index.html

使用iframe嵌入页面很方便,但必须在父页面指定iframe的高度。如果iframe页面内容的高度超过了指定高度,会出现滚动条,很难看。

如何让iframe自适应自身高度,让整个页面看起来像一个整体?

在HTML5之前,有很多使用JavaScript的Hack技巧,代码量大,而且很难通用。随着现代浏览器引入了新的ResizeObserver API[1],解决iframe高度问题就变得简单了。

我们假设父页面是index.html,要嵌入到iframe的子页面是target.html,在父页面中,先向页面添加一个iframe:

const iframe1 = document.createElement('iframe');
iframe1.src = 'target.html';
iframe1.onload = autoResize;
document.getElementById('sameDomain').appendChild(iframe1);

当iframe载入完成后,触发onload事件,然后自动调用autoResize()函数:

function autoResize(event) {
    // 获取iframe元素:
    const iframeEle = event.target;
    // 创建一个ResizeObserver:
    const resizeRo = new ResizeObserver((entries) => {
        let entry = entries[0];
        let height = entry.contentRect.height;
        iframeEle.style.height = height + 'px';
    });
    // 开始监控iframe的body元素:
    resizeRo.observe(iframeEle.contentWindow.document.body);
}

通过创建ResizeObserver,我们就可以在iframe的body元素大小更改时获得回调,在回调函数中对iframe设置一个新的高度,就完成了iframe的自适应高度。

跨域问题
ResizeObserver很好地解决了iframe的监控,但是,当我们引入跨域的iframe时,上述代码就失效了,原因是浏览器阻止了跨域获取iframe的body元素。

要解决跨域的iframe自适应高度问题,我们需要使用postMessage机制,让iframe页面向父页面主动报告自身高度。

假定父页面仍然是index.html,要嵌入到iframe的子页面是http://xyz/cross.html,在父页面中,先向页面添加一个跨域的iframe:

const iframe2 = document.createElement('iframe');
iframe2.src = 'http://xyz/cross.html';
iframe2.onload = autoResize;
document.getElementById('crossDomain').appendChild(iframe2);

在cross.html页面中,如何获取自身高度?

我们需要现代浏览器引入的一个新的MutationObserver API[2],它允许监控任意DOM树的修改。

在cross.html页面中,使用以下代码监控body元素的修改(包括子元素):

// 创建MutationObserver:
const domMo = new MutationObserver(() => {
    // 获取body的高度:
    let currentHeight = body.scrollHeight;
    // 向父页面发消息:
    parent.postMessage({
        type: 'resize',
        height: currentHeight
    }, '*');
});
// 开始监控body元素的修改:
domMo.observe(body, {
    attributes: true,
    childList: true,
    subtree: true
});

当iframe页面的body有变化时,回调函数通过postMessage向父页面发送消息,消息内容是自定义的。在父页面中,我们给window添加一个message事件监听器,即可收取来自iframe页面的消息,然后自动更新iframe高度:

window.addEventListener('message', function (event) {
    let eventData = event.data;
    if (eventData && eventData.type === 'resize') {
        iframeEle.style.height = eventData.height + 'px';
    }
}, false);

使用现代浏览器提供的ResizeObserver和MutationObserver API,我们就能轻松实现iframe的自适应高度。

文档:
ResizeObserver接口监视Element或者SVGElement尺寸的变化。 ↩︎
https://developer.mozilla.org/zh-CN/docs/Web/API/ResizeObserver#%E6%B5%8F%E8%A7%88%E5%99%A8%E5%85%BC%E5%AE%B9%E6%80%A7

MutationObserver接口提供了对DOM树更改的监视能力。 ↩︎
https://developer.mozilla.org/zh-CN/docs/Web/API/MutationObserver#%E6%B5%8F%E8%A7%88%E5%99%A8%E5%85%BC%E5%AE%B9%E6%80%A7

GitSite 可以将组织良好的 Markdown 文档和其他资源构建到静态网站,部署到 GitHub 页面等。
Markdown 文档
gitsite-cli 工具

部署
静态网站
GitHub 页面
GitLab 页面
CloudFlare页面
S3 网站托管
韦尔塞尔
自托管 Nginx
例:

GitHub 存储库: https://github.com/michaelliao/gitsite 可以部署到:

GitHub:https://gitsite.org
GitLab:https://gitlab.gitsite.org
Cloudflare:https://cloudflare.gitsite.org
Vercel: https://vercel.gitsite.org
GitSite 支持 Markdown 文档、嵌入式视频、数学表达式、ASCII 艺术、二维码、图表,甚至乐谱!


        $(".btn-copy-qrcode-image").click(function(e) {
            //复制图片功能
            var img = $('#' + $(this).data('target'))[0]   //tag: img
            var canvas = document.createElement('canvas')
            canvas.width = img.naturalWidth
            canvas.height = img.naturalHeight
            var ctx = canvas.getContext('2d');
            ctx.drawImage(img, 0, 0)
            canvas.toBlob(async blob => {
                const data = [
                    new ClipboardItem({
                        [blob.type]: blob,
                    }),
                ];
                await navigator.clipboard.write(data)
                    .then(
                        () => {
                            simpleDialog({
                                msg: '复制成功'
                            })
                        },
                        () => {
                            simpleDialog({
                                msg: '复制失败,请右键选择【复制图像】'
                            })
                        }
                    );
            });
        })

toBlob报错
图片跨域问题,img元素加上这个属性 crossorigin="anonymous"

Failed to execute 'toBlob' on 'HTMLCanvasElement': Tainted canvases may not be exported...