[javascript] Cross Browser Flash Detection in Javascript

Does anyone have an example of script that can work reliably well across IE/Firefox to detect if the browser is capable of displaying embedded flash content. I say reliably because I know its not possible 100% of the time.

This question is related to javascript flash cross-browser

The answer is


Minimum version I've ever used (doesn't check version, just Flash Plugin):

var hasFlash = function() {
    return (typeof navigator.plugins == "undefined" || navigator.plugins.length == 0) ? !!(new ActiveXObject("ShockwaveFlash.ShockwaveFlash")) : navigator.plugins["Shockwave Flash"];
};

Using Google Closure compiler goog.require('goog.userAgent.flash') library I created this 2 functions.

boolean hasFlash()

Returns if browser has flash.

function hasFlash(){
    var b = !1;
    function c(a) {if (a = a.match(/[\d]+/g)) {a.length = 3;}}
    (function() {
    if (navigator.plugins && navigator.plugins.length) {
        var a = navigator.plugins["Shockwave Flash"];
        if (a && (b = !0, a.description)) {c(a.description);return;}
        if (navigator.plugins["Shockwave Flash 2.0"]) {b = !0;return;}
    }
    if (navigator.mimeTypes && navigator.mimeTypes.length && (a = navigator.mimeTypes["application/x-shockwave-flash"], b = !(!a || !a.enabledPlugin))) {c(a.enabledPlugin.description);return;}
    if ("undefined" != typeof ActiveXObject) {
        try {
            var d = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");b = !0;c(d.GetVariable("$version"));return;
        } catch (e) {}
        try {
            d = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");b = !0;
            return;
        } catch (e) {}
        try {
            d = new ActiveXObject("ShockwaveFlash.ShockwaveFlash"), b = !0, c(d.GetVariable("$version"));
        } catch (e) {}
    }
    })();
    return b;
}

boolean isFlashVersion(version)

Returns if the flash version is greater than provided version

function isFlashVersion(version) {
    var e = String.prototype.trim ? function(a) {return a.trim()} : function(a) {return /^[\s\xa0]*([\s\S]*?)[\s\xa0]*$/.exec(a)[1]};
    function f(a, b) {return a < b ? -1 : a > b ? 1 : 0};
    var h = !1,l = "";
    function m(a) {a = a.match(/[\d]+/g);if (!a) {return ""}a.length = 3;return a.join(".")}
    (function() {
        if (navigator.plugins && navigator.plugins.length) {
            var a = navigator.plugins["Shockwave Flash"];
            if (a && (h = !0, a.description)) {l = m(a.description);return}
            if (navigator.plugins["Shockwave Flash 2.0"]) {h = !0;l = "2.0.0.11";return}
        }
        if (navigator.mimeTypes && navigator.mimeTypes.length && (a = navigator.mimeTypes["application/x-shockwave-flash"], h = !(!a || !a.enabledPlugin))) {l = m(a.enabledPlugin.description);return}
        if ("undefined" != typeof ActiveXObject) {
            try {
                var b = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");h = !0;l = m(b.GetVariable("$version"));return
            } catch (g) {}
            try {
                b = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");h = !0;l = "6.0.21";return
            } catch (g) {}
            try {
                b = new ActiveXObject("ShockwaveFlash.ShockwaveFlash"), h = !0, l = m(b.GetVariable("$version"))
            } catch (g) {}
        }
    })();
    var n = l;
    return (function(a) {
        var b = 0,g = e(String(n)).split(".");
        a = e(String(a)).split(".");
        for (var p = Math.max(g.length, a.length), k = 0; 0 == b && k < p; k++) {
            var c = g[k] || "",d = a[k] || "";
            do {
                c = /(\d*)(\D*)(.*)/.exec(c) || ["", "", "", ""];d = /(\d*)(\D*)(.*)/.exec(d) || ["", "", "", ""];
                if (0 == c[0].length && 0 == d[0].length) {break}
                b = f(0 == c[1].length ? 0 : parseInt(c[1], 10), 0 == d[1].length ? 0 : parseInt(d[1], 10)) || f(0 == c[2].length, 0 == d[2].length) || f(c[2], d[2]);c = c[3];d = d[3]
            } while (0 == b);
        }
        return 0 <= b
    })(version)
}

I agree with Max Stewart. SWFObject is the way to go. I'd like to supplement his answer with a code example. This ought to to get you started:

Make sure you have included the swfobject.js file (get it here):

<script type="text/javascript" src="swfobject.js"></script>

Then use it like so:

if(swfobject.hasFlashPlayerVersion("9.0.115"))
{
    alert("You have the minimum required flash version (or newer)");
}
else
{
    alert("You do not have the minimum required flash version");
}

Replace "9.0.115" with whatever minimum flash version you need. I chose 9.0.115 as an example because that's the version that added h.264 support.

If the visitor does not have flash, it will report a flash version of "0.0.0", so if you just want to know if they have flash at all, use:

if(swfobject.hasFlashPlayerVersion("1"))
{
    alert("You have flash!");
}
else
{
    alert("You do not flash :-(");
}

If you just wanted to check whether flash is enabled, this should be enough.

function testFlash() {

    var support = false;

    //IE only
    if("ActiveXObject" in window) {

        try{
            support = !!(new ActiveXObject("ShockwaveFlash.ShockwaveFlash"));
        }catch(e){
            support = false;
        }

    //W3C, better support in legacy browser
    } else {

        support = !!navigator.mimeTypes['application/x-shockwave-flash'];

    }

    return support;

}

Note: avoid checking enabledPlugin, some mobile browser has tap-to-enable flash plugin, and will trigger false negative.


If you are interested in a pure Javascript solution, here is the one that I copy from Brett:

function detectflash(){
    if (navigator.plugins != null && navigator.plugins.length > 0){
        return navigator.plugins["Shockwave Flash"] && true;
    }
    if(~navigator.userAgent.toLowerCase().indexOf("webtv")){
        return true;
    }
    if(~navigator.appVersion.indexOf("MSIE") && !~navigator.userAgent.indexOf("Opera")){
        try{
            return new ActiveXObject("ShockwaveFlash.ShockwaveFlash") && true;
        } catch(e){}
    }
    return false;
}

Detecting and embedding Flash within a web document is a surprisingly difficult task.

I was very disappointed with the quality and non-standards compliant markup generated from both SWFObject and Adobe's solutions. Additionally, my testing found Adobe's auto updater to be inconsistent and unreliable.

The JavaScript Flash Detection Library (Flash Detect) and JavaScript Flash HTML Generator Library (Flash TML) are a legible, maintainable and standards compliant markup solution.

-"Luke read the source!"


Carl Yestrau's JavaScript Flash Detection Library, here:

http://www.featureblend.com/javascript-flash-detection-library.html

... may be what you're looking for.


Code for one liner isFlashExists variable:

<script type='text/javascript'
    src='//ajax.googleapis.com/ajax/libs/swfobject/2.2/swfobject.js'> </script>

<script type='text/javascript'>
   var isFlashExists = swfobject.hasFlashPlayerVersion('1') ? true : false ;
   if (isFlashExists) {
    alert ('flash exists');
   } else {
    alert ('NO flash');
   }
</script>

Note that there is an alternative like this: swfobject.getFlashPlayerVersion();


Perhaps adobe's flash player detection kit could be helpful here?

http://www.adobe.com/products/flashplayer/download/detection_kit/


what about:

var hasFlash = function() {
    var flash = false;
    try{
        if(new ActiveXObject('ShockwaveFlash.ShockwaveFlash')){
            flash=true;
        }
    }catch(e){
        if(navigator.mimeTypes ['application/x-shockwave-flash'] !== undefined){
            flash=true;
        }
    }
    return flash;
};

You could use closure compiler to generate a small, cross-browser flash detection:

// ==ClosureCompiler==
// @compilation_level ADVANCED_OPTIMIZATIONS
// @output_file_name default.js
// @formatting pretty_print
// @use_closure_library true
// ==/ClosureCompiler==

// ADD YOUR CODE HERE
goog.require('goog.userAgent.flash');
if (goog.userAgent.flash.HAS_FLASH) {
    alert('flash version: '+goog.userAgent.flash.VERSION);
}else{
    alert('no flash found');
}

which results in the following "compiled" code:

var a = !1,
    b = "";

function c(d) {
    d = d.match(/[\d]+/g);
    d.length = 3;
    return d.join(".")
}
if (navigator.plugins && navigator.plugins.length) {
    var e = navigator.plugins["Shockwave Flash"];
    e && (a = !0, e.description && (b = c(e.description)));
    navigator.plugins["Shockwave Flash 2.0"] && (a = !0, b = "2.0.0.11")
} else {
    if (navigator.mimeTypes && navigator.mimeTypes.length) {
        var f = navigator.mimeTypes["application/x-shockwave-flash"];
        (a = f && f.enabledPlugin) && (b = c(f.enabledPlugin.description))
    } else {
        try {
            var g = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7"),
                a = !0,
                b = c(g.GetVariable("$version"))
        } catch (h) {
            try {
                g = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6"), a = !0, b = "6.0.21"
            } catch (i) {
                try {
                    g = new ActiveXObject("ShockwaveFlash.ShockwaveFlash"), a = !0, b = c(g.GetVariable("$version"))
                } catch (j) {}
            }
        }
    }
}
var k = b;
a ? alert("flash version: " + k) : alert("no flash found");

I know this is an old post, but I've been looking for a while and didn't find anything.
I've implemented the JavaScript Flash Detection Library. It works very well and it is documented for quick use. It literally took me 2 minutes. Here is the code I wrote in the header:

<script src="Scripts/flash_detect.js"></script>
<script type="text/javascript"> 
 if (!FlashDetect.installed) {
    alert("Flash is required to enjoy this site.");         
 } else {
    alert("Flash is installed on your Web browser.");
 }
</script>        

Detecting and embedding Flash within a web document is a surprisingly difficult task.

I was very disappointed with the quality and non-standards compliant markup generated from both SWFObject and Adobe's solutions. Additionally, my testing found Adobe's auto updater to be inconsistent and unreliable.

The JavaScript Flash Detection Library (Flash Detect) and JavaScript Flash HTML Generator Library (Flash TML) are a legible, maintainable and standards compliant markup solution.

-"Luke read the source!"


View the source at http://whatsmy.browsersize.com (lines 14-120).

Here is the abstracted cross browser code on jsbin for flash detection only, works on: FF/IE/Safari/Opera/Chrome.


Have created a small .swf which redirects. If the browser is flash enabled it will redirect.

package com.play48.modules.standalone.util;

import flash.net.URLRequest;


class Redirect {


static function main() {

    flash.Lib.getURL(new URLRequest("http://play48.com/flash.html"), "_self");

}

}

To create a Flash object standart-compliant (with JavaScript however), I recommend you take a look at

Unobtrusive Flash Objects (UFO)

http://www.bobbyvandersluis.com/ufo/index.html


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to flash

Assign command output to variable in batch file How to detect when a youtube video finishes playing? Error #2032: Stream Error How to embed a video into GitHub README.md? Want custom title / image / description in facebook share link from a flash app Flash CS4 refuses to let go How to add link to flash banner How can I detect if Flash is installed and if not, display a hidden div that informs the user? differences between using wmode="transparent", "opaque", or "window" for an embedded object on a webpage Best way to determine user's locale within browser

Examples related to cross-browser

Show datalist labels but submit the actual value Stupid error: Failed to load resource: net::ERR_CACHE_MISS Click to call html How to Detect Browser Back Button event - Cross Browser How can I make window.showmodaldialog work in chrome 37? Cross-browser custom styling for file upload button Flexbox and Internet Explorer 11 (display:flex in <html>?) browser sessionStorage. share between tabs? How to know whether refresh button or browser back button is clicked in Firefox CSS Custom Dropdown Select that works across all browsers IE7+ FF Webkit