Search code examples
javascriptcross-browserdjvu

How to check if the user's browser can view DJVU files using JavaScript


I am working on an app that generates compressed .djvu files and have a page for viewing the .djvu files.

I want to proactively check if the user's browser is able to open .djvu files and provide links to recommended plugins if their browser cannot open .djvu files.

The reason I want to be proactive about it and recommend plugins is because there is no universal solution to viewing .djvu files in-browser, and finding the right plugin is non-trivial.

My current solution (before writing any code) is to check the users browser and then check if specific plugins have been installed, but this is not very good or future proof. (e.g. if the user has a different / new plugin installed that I am not checking for)


Solution

  • This might not be a great solution, but it's functionally ok. It relies on plugin suffixes (supported file types) which I've noticed not all developers include, so it's not a catch-all solution.

    var numPlugins = navigator.plugins.length;
    var djvuPluginDetected = false;
    var djvuMimeTypes = ["image/x-djvu", "image/vnd-djvu", "image/x.djvu", "image/vnd.djvu"];   // Array of the different mime formats that may be used by plugins
    for (var i = 0; i < numPlugins; i++) {
        var plugin = navigator.plugins[i];
        var numMimeTypes = plugin.length;
        for (var j = 0; j < numMimeTypes; j++) {
            var mimeType = plugin[j];
            if (mimeType.suffixes.indexOf("djvu") > -1) {
                djvuPluginDetected = true;
            }
            if(djvuMimeTypes.indexOf(mimeType.type) > -1) {
                djvuPluginDetected = true;
            }
        }   // end for numMimeTypes
    }   // end for numPlugins
    // If there is no plugin that supports "djvu" was found then show the modal.
    if (!djvuPluginDetected) {
        $('#getdjvuPluginModal').modal('show');
    }
    

    This can also be used to check for plugins for different file types by searching the plugin > mime type > suffixes for a different file type, which may prove useful to someone else.

    e.g.

    if (mimeType && mimeType.suffixes.search("pdf") > -1)