wuiyang
wuiyang

Reputation: 429

store images in offline storage

I'm creating a speed dial extension for myself (I know there's a lot of speed dial extension, but most of them will display ads, and my antivirus threat them as PuP), I wanted to save website's logo image, let user either place one picture by themselves, or give the url of the picture.

I am stuck with how to save images in chrome's offline storage (https://developer.chrome.com/apps/offline_storage#table), there's no example for saving other file types.

How do I save picture on google chrome's offline storage?

Upvotes: 4

Views: 2052

Answers (2)

woxxom
woxxom

Reputation: 73556

  • Take a look at chrome.storage API:

    • 5MB data limit or unlimited if the extension has the unlimitedStorage permission
    • content scripts can directly access user data without the need for a background page.
    • It's asynchronous and therefore faster than the blocking and serial localStorage API.
    • User data can be stored as objects (the localStorage API stores data in strings). Only simple JSON-serializable objects are supported, though.
  • localStorage serializes everything so you'll have to convert the image to a dataurl first:

    var xhr = new XMLHttpRequest();
    xhr.open('GET', favicon_url);
    xhr.responseType = 'arraybuffer';
    xhr.onload = function(r) {
        if (xhr.status != 200) {
            return;
        }
        localStorage.icon = 'data:image/png;base64,' +
            btoa(String.fromCharCode.apply(null, new Uint8Array(xhr.response)));
    }
    xhr.send();
    

    This is a simplified example which assumes png image type.

  • chrome.fileSystem API might be a better choice. (not suitable for an extension as it's only for apps)
  • HTML5 FileSystem API: currently could be the best choice but the API is no longer maintained by W3C so it's unclear whether it stays in the future.

Upvotes: 5

Max Murphy
Max Murphy

Reputation: 1973

I would convert the image to a data URL. At that point it's just a string so it's easy to save. For examples of data URL images see: https://en.wikipedia.org/wiki/Data_URI_scheme#Examples

I usually convert images to data URLs on the command line with cat whatever.png | base64 but there are a number of websites that will do it for you, if you prefer.

Hope that helps.

To create images yourself (Remember to change the mime type to whatever you need): cat /apple/Downloads/80.png | printf "%s%s%s" '<img src="data:image/png;base64,' "$(base64 -w0)" '" alt="Red dot" />'

Examples of sites that will create data URLs for you:

I've made a fiddle to show how to use the file API to get an image as a data URL: https://jsfiddle.net/quvvtkwr/

Upvotes: 1

Related Questions