1

Say I have the following files in my unpacked Google Chrome extension:

  • manifest.json
  • my.extension.js
  • image.png

How do I check if image.png exists using Javascript in my.extension.js?

Edit:

I know (and I think it would work) that we could create an <img> element and use the onerror event OR use XMLHttpRequest to check for the existence but I am looking for a better(?) alternative solution, if any.

cychoi
  • 2,890
  • 3
  • 22
  • 31

2 Answers2

4
  1. Declare my.extension.js as event page or background page. (Content Scripts will not work with the following method since the chrome.* API provided in content scripts is limited)

  2. Use chrome.runtime.getPackageDirectoryEntry, as suggested by Xan, which is based on HTML 5 Filesystem API to access the resource files and thus you can check for the file existence therein.

manifest.json:

{
  "background": {
    "scripts": ["my.extension.js"],
    "persistent": false
  },
  "manifest_version": 2,
  "name": "Check Resource Existence",
  "version": "1.0",
}

my.extension.js:

filename = "image.png";

chrome.runtime.getPackageDirectoryEntry(function(storageRootEntry) {
  fileExists(storageRootEntry, filename, function(isExist) {
    if(isExist) {
      /* your code here */
    }
  });
});

function fileExists(storageRootEntry, fileName, callback) {
  storageRootEntry.getFile(fileName, {
    create: false
  }, function() {
    callback(true);
  }, function() {
    callback(false);
  });
}
Community
  • 1
  • 1
cychoi
  • 2,890
  • 3
  • 22
  • 31
  • Remark: a content script will work if the file is declared in `web_accessible_resources`, but then ANY origin can check for existence of that file (and consequently detect if your extension is installed) – Xan Nov 30 '14 at 13:44
2

You could look into chrome.runtime.getPackageDirectoryEntry:

chome.runtime.getPackageDirectoryEntry(function callback)

Returns a DirectoryEntry for the package directory.

You'll then be able to list files in your extension. For an example, see this answer.

That said, your XHR approach should also work. You just need to catch that error.

Community
  • 1
  • 1
Xan
  • 74,770
  • 16
  • 179
  • 206