Pergunta

Alguém tem um exemplo de script que pode trabalhar de forma confiável bem em IE / Firefox para detectar se o navegador é capaz de exibir conteúdo em Flash incorporado. Eu digo de forma confiável, porque eu sei que não é possível 100% do tempo.

Foi útil?

Solução

SWFObject é muito confiável. Eu usei-o sem problemas por um bom tempo.

Outras dicas

Eu concordo com Max Stewart . SWFObject é o caminho a percorrer. Eu gostaria de complementar sua resposta com um exemplo de código. Isso deve para você começar:

Certifique-se de ter incluído o arquivo swfobject.js (obtê-lo aqui ):

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

Em seguida, usá-lo assim:

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");
}

Substitua "9.0.115" com qualquer versão flash mínimo que você precisa. Eu escolhi 9.0.115 como um exemplo porque essa é a versão que acrescentou h.264 apoio.

Se o visitante não tem flash, ele irá informar uma versão em flash de "0.0.0", por isso, se você só quer saber se eles têm flash, use:

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

Eu sei que este é um post antigo, mas eu estive procurando por um tempo e não encontrou nada.
Eu tenho implementado o JavaScript Biblioteca detecção de flash . Ele funciona muito bem e é documentado para uso rápido. Ele literalmente me levou 2 minutos. Aqui está o código que eu escrevi no cabeçalho:

<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>        

Você pode usar fechamento compilador para gerar, a detecção de flash pequeno cross-browser:

// ==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');
}

que resulta no seguinte código "compilado":

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");

Versão mínima que já usei (não verifica a versão, apenas Flash Plugin):

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

JavaScript flash Detecção Biblioteca de Carl Yestrau, aqui:

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

... pode ser o que você está procurando.

Talvez kit de detecção de flash player da Adobe poderia ser útil aqui?

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

Detecção e incorporação do Flash dentro de um documento web é uma tarefa surpreendentemente difícil.

Fiquei muito decepcionado com a marcação qualidade e não-compatível com as normas geradas a partir de ambas as soluções da Adobe SWFObject e. Além disso, o meu teste encontrado atualizador automático da Adobe para ser inconsistentes e pouco confiáveis.

A Biblioteca detecção do Flash JavaScript (Flash Detect) e JavaScript flash HTML Generator Biblioteca (flash TML) são uma solução de marcação compatível legível, de fácil manutenção e normas rel = "noreferrer" .

- "Lucas ler a fonte!"

código para a variável isFlashExists um forro:

<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 que existe uma alternativa como esta: swfobject.getFlashPlayerVersion();

Ver a fonte em http://whatsmy.browsersize.com (linhas 14-120).

Aqui é o navegador cruz abstraída código em jsbin para única de detecção do Flash , trabalham em:. FF / IE / Safari / Opera / Chrome

o que acontece com:

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;
};

Se você está interessado em uma solução Javascript puro, aqui é o que eu copiar de 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;
}

Se você só queria verificar se o flash é ativado, isso deve ser suficiente.

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;

}

Nota:. Verificação evitar enabledPlugin , algum navegador móvel tem tap-to-permitem plugin flash, e irá desencadear falsos negativos

Para criar um objeto Flash Standart-compatível (com JavaScript no entanto), eu recomendo que você dê uma olhada

Unobtrusive flash Objetos (UFO)

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

criaram um pequeno .swf que redirecionamentos. Se o navegador é o Flash habilitado que irá redirecionar.

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");

}

}

Usando o compilador goog.require ( 'goog.userAgent.flash') biblioteca do Google Closure Eu criei este 2 funções.

boolean hasFlash ()

Retorna se o navegador tem de 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 (versão)

Retorna se a versão flash é maior do que a versão fornecida

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)
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top