从文件输入中访问.svg文件's contentDocument - Chrome上的跨框架问题
Accessing .SVG file's contentDocument from file input - cross frame issue on Chrome
我试图通过JavaScript访问SVG的contentDocument
(并更改特定路径的填充颜色,但我没有问题)。SVG来自用户输入。每当我尝试访问contentDocument
时,我都会得到错误:
(index):41 Uncaught DOMException: Failed to read 'contentDocument'property from ' htmllobjectelement ':阻塞了一个有origin的框架"http://localhost"访问跨原点帧
正如您所看到的,我使用的是本地服务器,但是在本地访问文件时结果是相同的。下面是我的代码:
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
我知道这可以通过实际上将文件上传到服务器,然后在本地访问它(如在服务器上)来修复,但是有没有一种方法可以在不引入服务器端脚本和上传的情况下使其工作?
将本地svg文件加载到DOM的另一种方法是:
- 在选择后将文件读取为文本(假设它是ASCII或utf-8编码)。
- 将内容写入
iframe
对象的文档 - 从iframe中获取svgElement
概念代码/strong>
这段代码使用了一个示例字符串而不是执行步骤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();
相关文章:
- Chrome加载旧版本的Javascript文件
- 通过命令行/批处理文件打开页面时,将javascript代码注入Google Chrome
- 从Chrome扩展名中的popup.html文件在background.js文件中运行一个函数
- 如何在Google chrome安全首选项文件中创建扩展安全哈希代码
- 清单文件中的update_url禁用了我的chrome扩展
- Blueimp文件上传程序-Chrome文件夹上传限制
- 通过Android Chrome浏览器下载文件
- Chrome控制台-整个文件的断点
- 如何动态添加或删除Chrome扩展、内容脚本、javascript文件
- 内容安全策略指令:;脚本src'self'blob:文件系统:chrome扩展资源:“;获取是否时
- Chrome审核:在外部CSS文件之间的头中发现了1个内联脚本块&”;
- HTML5视频无法在chrome上工作,在服务器上托管后的IE,mov文件中的视频(quicktime格式)
- Chrome中的本地文件访问
- 如何用Javascript从Chrome iOS下载blob文件
- 如何从 Chrome 中的文件输入中删除“未选择文件”工具提示
- Chrome APP/扩展程序从网址下载文件
- 如何通过chrome扩展名获取所有CSS和Javascript文件
- 加载本地XML文件- Chrome 14
- 获取缓存文件chrome扩展名
- 媒体源Api不能用于自定义webm文件(Chrome版本23.0.1271.97 m)