简体   繁体   中英

Chrome extension, file from string?

I'm building chrome extension for watching videos.

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).

Is there a good way to create a file from string in chrome exstension / javascript, and than accessing it via url/path?

Thx

Creating an URL from a string is very easy with the Blob constructor and URL.createObjectURL :

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. Just set 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 :

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM