将图像存储在离线存储中

wui*_*ang 4 local-storage google-chrome-extension

我正在为自己创建一个快速拨号扩展(我知道有很多快速拨号扩展,但大多数会显示广告,我的防病毒威胁他们作为PuP),我想保存网站的徽标图像,让用户放置一张图片自己,或者给出图片的网址.

我不知道如何在chrome的离线存储中保存图像(https://developer.chrome.com/apps/offline_storage#table),没有保存其他文件类型的示例.

如何在google chrome的离线存储中保存图片?

wOx*_*xOm 5

  • 看看chrome.storage API:

    • 如果扩展程序具有unlimitedStorage权限,则为5MB数据限制或无限制
    • 内容脚本可以直接访问用户数据,而无需后台页面.
    • 它是异步的,因此比阻塞和串行localStorage API更快.
    • 用户数据可以存储为对象(localStorage API将数据存储在字符串中).但是,仅支持简单的JSON可序列化对象.
  • localStorage 序列化所有内容,因此您必须先将图像转换为dataurl:

    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();
    
    Run Code Online (Sandbox Code Playgroud)

    这是一个假设png图像类型的简化示例.

  • chrome.fileSystem API可能是更好的选择.(不适合扩展,因为它仅适用于应用)
  • HTML5 FileSystem API:目前可能是最佳选择,但W3C不再维护API,因此不清楚它是否会保留在未来.