[英]Chrome extension, file from string?
I'm building chrome extension for watching videos. 我正在构建用于观看视频的chrome扩展程序。
I have problem with adding subtitles and captions to video. 我在为视频添加字幕和字幕时遇到问题。 I have subtitle as string (from ajax call), and problem is that
<track>
tag in html5 requires a file, (url to file). 我有字幕作为字符串(来自ajax调用),问题是html5中的
<track>
标记需要一个文件,(url to file)。
Is there a good way to create a file from string in chrome exstension / javascript, and than accessing it via url/path? 有没有一种很好的方法从chrome exstension / javascript中的字符串创建文件,而不是通过url / path访问它?
Thx 谢谢
Creating an URL from a string is very easy with the Blob
constructor and URL.createObjectURL
: 使用
Blob
构造函数和URL.createObjectURL
可以非常轻松地从字符串创建URL:
var content = 'some string';
var url = URL.createObjectURL(new Blob([content], { type: 'text/plain' }));
If you're using AJAX, then you don't need to do a string-to-blob conversion. 如果您使用的是AJAX,那么您不需要进行字符串到blob的转换。 Just set
responseType = 'blob';
只需设置
responseType = 'blob';
directly: 直:
var x = new XMLHttpRequest();
x.open('GET', 'http://example.com/');
x.responseType = 'blob';
x.onload = function() {
var url = URL.createObjectURL(x.response);
// ...
};
x.send();
Instead of creating a file, you can try generating a data URI : 您可以尝试生成数据URI ,而不是创建文件:
src = 'data:text/plain,' + encodeURIComponent(subtitleString);
or: 要么:
src = 'data:text/plain;base64,' + btoa(subtitleString);
You'll need to add encoding info if you are dealing with non US-ASCII subtitles. 如果您要处理非US-ASCII字幕,则需要添加编码信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.