You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

iframe重载后DOMContentLoaded代码失效,card2背景复原问题求助

问题原因

你的代码仅在dashboard页面的DOM首次加载完成时执行一次。当用户调整按钮顺序触发iframe重载时,dashboard本身的DOM并未重新加载,DOMContentLoaded事件不会再次触发,导致新加载的iframe内容没有被注入移除背景的样式,card2的白色背景和阴影因此重新显现。

修复方案

将逻辑改为监听iframe的load事件,这样无论iframe是首次加载还是后续重载,只要加载完成就会执行样式修改:

window.addEventListener('DOMContentLoaded', (event) => {
  const iframe = document.getElementById("biolink_preview_iframe");
  
  // 定义样式注入函数
  function injectCustomStyles() {
    const iframeContent = iframe.contentDocument;
    if (iframeContent) {
      // 检查是否已添加过自定义样式,避免重复注入
      const existingStyle = iframeContent.querySelector('#custom-card-style');
      if (!existingStyle) {
        const style = document.createElement('style');
        style.id = 'custom-card-style';
        style.textContent = '.card2{background-color: unset !important;box-shadow: none !important}';
        iframeContent.body.appendChild(style);
      }
    }
  }

  // 如果iframe已经加载完成,直接执行一次
  if (iframe.contentDocument?.readyState === 'complete') {
    injectCustomStyles();
  }
  
  // 监听iframe的load事件,重载时自动执行
  iframe.addEventListener('load', injectCustomStyles);
});

补充说明

  • 给样式标签添加唯一IDcustom-card-style,可以避免每次iframe加载都重复插入相同样式,减少页面冗余。
  • 先判断iframe的内容文档是否存在,能避免跨域限制或加载未完成时出现报错。

内容的提问来源于stack exchange,提问作者Sergejs

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 00:22:07