getSVGDocument在FireFox和Chrome中返回null

getSVGDocument returns null in FireFox and Chrome

本文关键字:返回 null Chrome FireFox getSVGDocument      更新时间:2023-09-26

getSVGDocument坏了吗?过时了吗?

因为当我"运行"以下内容时:

<!DOCTYPE HTML>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>SVG Embedded - Chapter 07</title>
  <link rel="stylesheet" href="../bootstrap/css/bootstrap.css">
  <link rel="stylesheet" href="../assets/style.css">
  <style>
    body { margin: 1em; }
    svg { border: 1px solid silver; }
    rect, text { fill: white; }
    circle { fill: black; }
  </style>
</head>
<body>
<svg version="1.1" xmlns="http://www.w3.org/2000/svg" height="200" width="300">
<rect width="100%" height="100%" fill="black" />
<circle cx="150" cy="100" r="80" fill="white" />
<text x="150" y="125" font-size="60" text-anchor="middle">SVG</text>
</svg>
<embed src="../assets/svg.svg"></embed>
<object data="../assets/svg.svg"></object>
<script>
document.addEventListener('DOMContentLoaded',function() {
  'use strict';
var rects = document.querySelectorAll('svg'),
      embed = document.querySelector('embed').getSVGDocument();
console.log(rects.length);
  console.log(embed,embed.childNodes.length);
},false);
</script>
</body>
</html>
然后等待所有3个SVG (加载和)显示,并在控制台输入:document.getElementsByTagName('embed')[0].getSVGDocument()它返回null

整页(含文件)可在此下载:https://github.com/stopsatgreen/modernwebbook/blob/master/Code%20Examples/Chapter%2007/svg-embedded.html

注意:我会尝试让页面在JS Bin中运行。

编辑:

问题是这样的吗?在本地主机上访问时SVG不工作。为什么?

如果是这样,如何修复它不配置(本地)web服务器?

不推荐使用getSVGDocument()方法。建议使用contentDocument属性。

看到

找到了如何解决这个问题,这是一个与安全相关的问题。

Chrome

首先关闭所有运行的chrome实例。然后用命令行标志启动Chrome可执行文件:

铬——allow-file-access-from-files

在Windows上,最简单的可能是创建一个添加了标志的特殊快捷方式(右键单击快捷方式-> properties -> target)。

Firefox

转到about:config找到security.fileuri。strict_origin_policy参数设置为false

明白了:https://github.com/mrdoob/three.js/wiki/How-to-run-things-locally