首页 > 解决方案 > 使用 Svelte 访问 iframe 内容

问题描述

我正在尝试访问 iframe 中的 head 元素以更改样式。但是我能想到的一切都行不通。
这是我当前的代码:

<script>
  let frame;
  onMount(() => {
    frame.addEventListener('load', onLoad());
  })
  function onLoad() {
    let head = frame.contentDocument.head || frame.contentWindow.document.head;
    console.log(head);
  }
</script>

<iframe bind:this={frame} src="src_here" title="preview" />

这将成功记录 iframe 但innerHTML为空白。

标签: iframestylingheadsvelte

解决方案


我认为您不能很好地访问 head 元素。

尝试这样的事情:

function onLoad() {
    const head = frame.contentDocument.querySelector('head');
    console.log(head);
}

推荐阅读