阿里云主机折上折
  • 微信号
Current Site:Index > Methods for embedding Flash

Methods for embedding Flash

Author:Chuan Chen 阅读数:30249人阅读 分类: HTML

Flash was once the mainstream technology for embedding multimedia content in web pages. Although it is gradually being replaced by HTML5, understanding its implementation methods is still necessary for certain legacy systems. Below is a detailed introduction to several common methods for embedding Flash.

Using <object> and <embed> Tags

The most traditional method is to embed Flash files using the <object> and <embed> tags. This approach offers good compatibility but requires using both tags simultaneously to ensure proper functionality across different browsers.

<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" 
        width="550" height="400" 
        codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0">
    <param name="movie" value="example.swf" />
    <param name="quality" value="high" />
    <param name="allowScriptAccess" value="always" />
    <embed src="example.swf" 
           quality="high" 
           width="550" height="400" 
           type="application/x-shockwave-flash" 
           pluginspage="http://www.macromedia.com/go/getflashplayer" 
           allowScriptAccess="always" />
</object>

Using the SWFObject Library

SWFObject is a JavaScript library specifically designed for embedding Flash content. It provides a more concise API and better browser compatibility.

First, include the SWFObject library:

<script src="https://ajax.googleapis.com/ajax/libs/swfobject/2.2/swfobject.js"></script>

Then use the following code to embed Flash:

swfobject.embedSWF(
    "example.swf",  // Path to the SWF file
    "flashContainer",  // Container ID
    "550",  // Width
    "400",  // Height
    "9.0.0",  // Minimum required Flash Player version
    "expressInstall.swf",  // Optional: Express Install SWF for upgrades
    {},  // Flash variables
    {  // Parameters
        quality: "high",
        allowScriptAccess: "always",
        allowFullScreen: "true"
    },
    {  // Attributes
        id: "exampleFlash",
        name: "exampleFlash"
    }
);

Using Pure JavaScript for Dynamic Creation

Without relying on third-party libraries, you can also dynamically create Flash embedding code using pure JavaScript:

function embedFlash(swfPath, containerId, width, height) {
    var container = document.getElementById(containerId);
    var flashHTML = '<object type="application/x-shockwave-flash" data="' + swfPath + '" width="' + width + '" height="' + height + '">';
    flashHTML += '<param name="movie" value="' + swfPath + '" />';
    flashHTML += '<param name="quality" value="high" />';
    flashHTML += '<param name="allowScriptAccess" value="always" />';
    flashHTML += '</object>';
    container.innerHTML = flashHTML;
}

// Example usage
embedFlash("example.swf", "flashContainer", 550, 400);

Handling Browser Compatibility Issues

As modern browsers increasingly drop support for Flash, fallback solutions should be considered. You can add alternative content within the <object> tag:

<object ...>
    <!-- Flash embedding code -->
    <param ...>
    <embed ...>
    <!-- Fallback content -->
    <div class="flash-alternative">
        <p>Your browser does not support Flash. Please <a href="example.html">click here</a> to view the HTML5 version.</p>
    </div>
</object>

Using HTML5's <embed> Tag

Although the <embed> tag is not new in HTML5, its usage is more standardized in HTML5:

<embed src="example.swf" 
       width="550" 
       height="400" 
       type="application/x-shockwave-flash" 
       pluginspage="http://www.adobe.com/go/getflashplayer" 
       allowScriptAccess="always" 
       quality="high" />

Embedding Flash via iframe

Another method is to place the Flash file in a separate HTML page and embed it using an iframe:

<iframe src="flash_content.html" width="550" height="400" frameborder="0"></iframe>

Where flash_content.html contains the Flash embedding code:

<!DOCTYPE html>
<html>
<head>
    <title>Flash Content</title>
</head>
<body>
    <object ...>
        <!-- Flash embedding code -->
    </object>
</body>
</html>

Passing Parameters with FlashVars

You can pass parameters to the Flash file using FlashVars:

<object ...>
    <param name="movie" value="example.swf" />
    <param name="FlashVars" value="param1=value1&param2=value2" />
    <embed ... FlashVars="param1=value1&param2=value2" />
</object>

Or with SWFObject in JavaScript:

swfobject.embedSWF("example.swf", "flashContainer", "550", "400", "9.0.0", 
    null, 
    {  // Flash variables
        param1: "value1",
        param2: "value2"
    },
    ...);

Detecting Flash Player Installation

You can use JavaScript to detect whether the user's browser has Flash Player installed:

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

if (!hasFlash()) {
    document.getElementById('flashContainer').innerHTML = 
        '<p>Please install Flash Player to view this content.</p>';
}

Responsive Flash Embedding

To make Flash content adapt to different screen sizes, use CSS and percentage widths:

<div class="flash-wrapper">
    <object ... width="100%" height="100%">
        <!-- Flash embedding code -->
    </object>
</div>

<style>
    .flash-wrapper {
        width: 100%;
        height: 0;
        padding-bottom: 75%; /* 4:3 aspect ratio */
        position: relative;
    }
    .flash-wrapper object {
        position: absolute;
        width: 100%;
        height: 100%;
    }
</style>

Using Express Install for Automatic Updates

SWFObject supports Express Install, which can prompt users to upgrade if their Flash Player version is too old:

swfobject.embedSWF("example.swf", "flashContainer", "550", "400", "9.0.0", 
    "expressInstall.swf",  // Express Install SWF file
    ...);

Ensure the expressInstall.swf file is in the same directory as the main SWF file.

Handling Fullscreen Mode

To allow Flash content to enter fullscreen mode, set the allowFullScreen parameter:

<object ...>
    <param name="allowFullScreen" value="true" />
    <embed ... allowFullScreen="true" />
</object>

Or with SWFObject:

swfobject.embedSWF(..., {
    allowFullScreen: "true"
}, ...);

Cross-Domain Communication Security Settings

If Flash needs to communicate with JavaScript across domains, configure the crossdomain.xml file and the allowScriptAccess parameter:

<object ...>
    <param name="allowScriptAccess" value="always" />
    <embed ... allowScriptAccess="always" />
</object>

Also, place a crossdomain.xml file in the server's root directory:

<?xml version="1.0"?>
<cross-domain-policy>
    <allow-access-from domain="*" />
</cross-domain-policy>

Using Flash Player Detection and Installation

Adobe provides official tools for Flash Player detection and installation:

<script src="//ajax.googleapis.com/ajax/libs/swfobject/2.2/swfobject.js"></script>
<script>
    var flashvars = {};
    var params = {
        menu: "false",
        scale: "noScale",
        allowFullscreen: "true",
        allowScriptAccess: "always",
        bgcolor: ""
    };
    var attributes = {
        id:"myFlashContent"
    };
    swfobject.embedSWF(
        "myContent.swf", 
        "altContent", 
        "550", 
        "400", 
        "10.0.0", 
        "expressInstall.swf", 
        flashvars, 
        params, 
        attributes
    );
</script>
<div id="altContent">
    <h1>Alternative content</h1>
    <p><a href="http://www.adobe.com/go/getflashplayer">Get Adobe Flash player</a></p>
</div>

Handling Flash on Mobile Devices

Since most mobile devices do not support Flash, special handling is required:

<object ...>
    <!-- Flash embedding code -->
    <div class="no-flash">
        <p>Mobile devices do not support Flash. Please use a desktop browser.</p>
        <!-- Or provide HTML5 fallback content -->
        <video controls>
            <source src="video.mp4" type="video/mp4">
        </video>
    </div>
</object>

Using Flash with JavaScript Communication

Flash can communicate bidirectionally with JavaScript via ExternalInterface:

ActionScript side:

import flash.external.ExternalInterface;

// Call a JavaScript function
ExternalInterface.call("jsFunction", "parameter");

// Register a function for JavaScript to call
ExternalInterface.addCallback("flashFunction", function(param:String):String {
    return "Flash received: " + param;
});

JavaScript side:

// Call a function in Flash
document.getElementById("myFlash").flashFunction("parameter");

// JavaScript function called by Flash
function jsFunction(param) {
    console.log("JavaScript received: " + param);
}

Performance Optimization Tips

To improve the loading and performance of Flash content:

  1. Preload SWF files:
swfobject.preloadSWF("example.swf");
  1. Use smaller SWF file sizes

  2. Optimize ActionScript code

  3. Use a loading progress bar:

<div id="loading">
    <p>Loading... <span id="loadPercent">0</span>%</p>
</div>
<script>
function showLoadProgress(percent) {
    document.getElementById("loadPercent").innerHTML = percent;
}
</script>

ActionScript side:

loaderInfo.addEventListener(ProgressEvent.PROGRESS, function(e:ProgressEvent):void {
    var percent:Number = Math.round(e.bytesLoaded / e.bytesTotal * 100);
    ExternalInterface.call("showLoadProgress", percent);
});

Handling Keyboard Events

To capture keyboard events in Flash, set the wmode parameter:

<object ...>
    <param name="wmode" value="opaque" />
    <embed ... wmode="opaque" />
</object>

Or with SWFObject:

swfobject.embedSWF(..., {
    wmode: "opaque"
}, ...);

Using Flash Local Storage

Flash can use SharedObject for local storage:

ActionScript side:

var so:SharedObject = SharedObject.getLocal("myData");
so.data.userName = "John";
so.flush();

JavaScript can access this data via ExternalInterface.

Debugging Flash Content

To debug embedded Flash content, use the following methods:

  1. Use Flash Debug Player
  2. Catch errors in JavaScript:
try {
    // Flash operation code
} catch (e) {
    console.error("Flash error: " + e.message);
}
  1. Use browser developer tools to inspect Flash objects

Handling Different DPI Screens

To ensure Flash content appears sharp on high-DPI screens:

<object ...>
    <param name="scale" value="exactFit" />
    <embed ... scale="exactFit" />
</object>

Or dynamically adjust dimensions with JavaScript:

function adjustFlashSize() {
    var dpi = window.devicePixelRatio || 1;
    var flashObj = document.getElementById("myFlash");
    if (flashObj) {
        flashObj.width = 550 * dpi;
        flashObj.height = 400 * dpi;
    }
}
window.addEventListener("resize", adjustFlashSize);
adjustFlashSize();

本站部分内容来自互联网,一切版权均归源网站或源作者所有。

如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn

Front End Chuan

Front End Chuan, Chen Chuan's Code Teahouse 🍵, specializing in exorcising all kinds of stubborn bugs 💻. Daily serving baldness-warning-level development insights 🛠️, with a bonus of one-liners that'll make you laugh for ten years 🐟. Occasionally drops pixel-perfect romance brewed in a coffee cup ☕.