Search code examples
javascriptflashdetectfile-type

how to detect if a URL points to a SWF


Is there a way (preferrably using JavaScript) to determine whether a URL is to a SWF or a JPG?

The obvious answer is to sniff the filename for ".jpg" or ".swf" but I'm dealing with banners that are dynamically decided by the server and usually have a lot of parameters and generally don't include an extension.

so i'm wondering if I could load the file first and then read it somehow to determine whether it's SWF or JPG, and then place it, because the JavaScript code I'd need to display a JPG vs a SWF is very different.

Thanks!


Solution

  • You could use javascript to detect if it is a image by creating a dynamic img-tag.

    function isImage(url, callback) {
        var img = document.createElement('img');
        img.onload = function() {
            callback(url);
        }
        img.src = url;
    }
    

    And then calling it with:

    isImage('http://animals.nationalgeographic.com/staticfiles/NGS/Shared/StaticFiles/animals/images/primary/bald-eagle-head.jpg', function(url) { alert(url + ' is a image'); });
    

    Update This version will always execute the callback with a boolean value.

            function isImage(url) {
            var img = document.createElement('img');
            img.onload = function() {
                isImageCallback(url, true);
            }
            img.onerror = function() {
                isImageCallback(url, false);
            }
            img.src = url;
        }
    
        function isImageCallback(url, result) {
            if (result)
                alert(url + ' is an image');
            else
                alert(url + ' is not an image');
        }
    

    Put your logic in the isImageCallback function.