首页 > 解决方案 > 使用 Electron 重新加载后无法访问 SVG DOM

问题描述

我在 Electron 应用程序的页面上放置了一个交互式 SVG 元素,因此我需要使用 Javascript 访问外部 SVG 文档中的元素。在我重新加载页面之前,一切都按预期工作。重新加载后,我无法从内联或外部脚本访问外部 SVG DOM,也无法从控制台访问。我错过了什么还是这是一个错误?

为了进行测试,我根据 Electron 入门页面从头开始创建了一个未打包的 Electron 应用程序(版本 5.0.4 和 5.0.6)。然后我放入了三个相同的简单 SVG,一个带有“object”标签,一个带有“embed”标签,还有一个是内联的。我编写了一些代码,以便在每个 SVG 加载后将第一个元素发送到控制台。在最初启动应用程序时,所有三个元素都按预期显示在页面和控制台中。

然后我使用 Ctrl+R(或 Ctrl+Shift+R)重新加载应用程序,虽然所有三个元素仍然出现在页面上,但只有内联 SVG 中的元素出现在控制台中。另外两个给出关于读取 null 属性的错误。在“object”或“embed”标签上通过控制台使用 contentDocument 或 getSVGDocument() 分别返回 null,而在重新加载之前它们没有。使用 Jquery 而不是 getElementById 方法时也是如此。我什至无法通过 Chromium 开发者控制台中的元素资源管理器找到外部文档。

这是我刚刚描述的代码:

<object id="object" data="bookmark.svg" type="image/svg+xml"></object>

<embed id="embed" src="bookmark.svg" type="image/svg+xml"></embed>

<svg id="inline" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" x="0px" y="0px" viewBox="0 0 24 24" style="enable-background:new 0 0 24 24;" xml:space="preserve" width="96px" height="96px">
  <g id="Sharp_3_">
    <path d="M16,2v10l-3-2l-3,2V2H6C4.895,2,4,2.895,4,4v15c1,0,0.895-2,2-2h14V2H16z"/>
    <path style="fill:none;stroke:#000000;stroke-width:2;stroke-miterlimit:10;" d="M20,17H7c-1.105,0-2,0.895-2,2s0.895,2,2,2h13"/>
  </g>
</svg>

<script>
  document.getElementById("object").onload = function() {
    console.log(document.getElementById("object").contentDocument.children[0].children[0]);
  }

  document.getElementById("embed").onload = function() { 
    console.log(document.getElementById("embed").getSVGDocument().children[0].children[0]);
  }

  console.log(document.getElementById("inline").children[0]);
</script>

控制台在重新加载之前返回以下内容:

index.html:23  <g id="Sharp_3_">...</g>

index.html:26  <g id="Sharp_3_">...</g>

index.html:28  <g id="Sharp_3_">...</g>

重新加载后:

index.html:28  <g id="Sharp_3_">...</g>

index.html:23  Uncaught TypeError: Cannot read property 'children' of null at HTMLObjectElement.document.getElementById.onload (index.html:23)

index.html:26  Uncaught TypeError: Cannot read property 'children' of null at HTMLObjectElement.document.getElementById.onload (index.html:26)

我希望这在重新加载后会产生相同的结果——即使它总是工作或不工作——这就是让我认为这是一个错误的原因。但是,我是 Electron 的新手,很可能会遗漏一些我还没有遇到的关于安全性或应用程序结构的内容。我已经做了一些查找,但还没有找到关于这个问题的具体内容。我确实找到了一些关于重新加载导致空白页面或缓存导致 SVG 出现问题的内容,但我不知道如何将其应用于此问题。

我永远无法重新加载并找到一种方法来阻止用户重新加载,但这会大大降低我的迭代速度。我可以在 SVG 中编写脚本,但我有多个 SVG 需要同时响应相同的代码。任何其他解决方法或解决方案将不胜感激,但这可能只是一个错误,我不能确定。

标签: javascripthtmlsvgelectron

解决方案


推荐阅读