我正在尝试通过 JavaScript 访问 SVG 的 contentDocument
(并更改特定路径的填充颜色,但我没有问题)。 SVG 来自用户输入。每当我尝试访问 contentDocument
时,都会收到错误:
(index):41 Uncaught DOMException: Failed to read the 'contentDocument' property from 'HTMLObjectElement': Blocked a frame with origin "http://localhost" from accessing a cross-origin frame.
正如您所看到的,我正在使用本地服务器,但在本地访问文件时结果是相同的。这是我的代码:
document.getElementById("input-image").addEventListener("load", function () {
console.log("image loaded");
let svgDoc = this.contentDocument;
}, false);
var src = document.getElementById("file-input");
var target = document.getElementById("input-image");
var fr = new FileReader();
fr.onload = function (e) {
target.data = this.result;
};
src.addEventListener("change", function () {
fr.readAsDataURL(src.files[0]);
});
和 HTML:
<object data="" type="image/svg+xml" id="input-image" width="100%" height="100%"></object>
<input id="file-input" type="file" accept=".svg" />
这是一个 jsFiddle .
我知道可以通过将文件实际上传到服务器然后在本地访问它(如在服务器上)来解决这个问题,但是有没有办法让它在不引入服务器端脚本和上传的情况下工作? p>
最佳答案
将本地 svg 文件加载到 DOM 中的替代方法的建议是
- 选择后将文件读取为文本(我们假设它是 ASCII 或 utf-8 编码)。
- 将内容写入
iframe
对象的文档 - 从 iframe 中获取 svgElement。
概念代码
此代码使用示例字符串而不是执行步骤 1。
let svgTest = function() {
let iframe = document.createElement("iframe");
document.body.appendChild(iframe); // insert it in the document, somewhere
// normally read the svg as text, but here just use an example from
// https://developer.mozilla.org/en-US/docs/Web/SVG/Tutorial/Getting_Started
let result = `
<svg version="1.1"
baseProfile="full"
width="300" height="200"
xmlns="http://www.w3.org/2000/svg">
<rect width="100%" height="100%" fill="red" />
<circle cx="150" cy="100" r="80" fill="green" />
<text x="150" y="125" font-size="60" text-anchor="middle" fill="white">SVG</text>
</svg>
`;
// write it to the iframe and close the document
let doc = iframe.contentWindow.document;
doc.write(result)
doc.close();
// get the svgElement
let svgElement = doc.getElementsByTagName("svg")[0];
let svgRect = svgElement.getBoundingClientRect();
// set iframe size (may need adjustment)
doc.body.style.margin = "0";
iframe.width = svgRect.width;
iframe.height = svgRect.height;
}; //end of svgTest
svgTest();
关于javascript - 从文件输入访问 .SVG 文件的 contentDocument - Chrome 上的跨框架问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40620981/