Accessing an ActionScript function via Javascript - javascript

I'm trying to call a function in an action script using the ExternalInterface.addCallback API, but I can't seem to get it to work. Here's what I have:
ActionScript:
//MyClass.as
package {
import flash.display.Sprite;
import flash.external.ExternalInterface;
public class MyClass extends Sprite
{
public function MyClass()
{
ExternalInterface.addCallback('getStringJS', getStringAS);
}
public function getStringAS():String
{
return "Hello World!";
}
}
}
NOTE: I'm compiling this into an swf using the flex mxmlc compiler if that matters.
HTML/Javascript:
<!doctype html>
<html>
<head>
<title>User Identification</title>
<head>
<body>
<object id="MyClass" name="MyClass" type="application/x-shockwave-flash" data="MyClass.swf" width="1" height="1">
<param name="movie" value="MyClass.swf">
<embed src="MyClass.swf" width="1" height="1">
</object>
<script type="text/javascript">
var flash = document.getElementById("MyClass");
var str = flash.getStringJS();
alert(str);
</script>
</body>
</html>
The error I'm getting is:
Uncaught TypeError: Object #<HTMLObjectElement> has no method 'getStringJS'
I also tried adding in a timeout in case the swf file wasn't loading, but I didn't have any success with that method either.
Any thoughts?
Cheers,
Mike

I figured it out. The key way to signal the javascipt through ExternalInterface.call so we know for sure that the swf is loaded. The most "Universal" way to do this is as follows:
MyClass.as
//MyClass.as
package {
import flash.display.Sprite;
import flash.external.ExternalInterface;
public class MyClass extends Sprite
{
public function MyClass()
{
ExternalInterface.addCallback('getStringJS', getStringAS);
if (ExternalInterface.available) {
ExternalInterface.call("isConnectedFlex");
}
}
public function getStringAS():String
{
return "Hello World!";
}
}
}
index.html
<!doctype html>
<html>
<head>
<title>User Identification</title>
<head>
<body>
<object id="MyClass" name="MyClass" type="application/x-shockwave-flash" data="MyClass.swf" width="1" height="1">
<param name="movie" value="MyClass.swf">
<embed src="MyClass.swf" width="1" height="1">
</object>
<script type="text/javascript">
var flash = document.getElementById("MyClass");
function isConnectedFlex() {
var str = flash.getStringJS();
alert(str);
}
</script>
</body>
</html>

I think the issue is a matter of the flash not being loaded. I tried your code using the window.onload event and it worked for me:
The flash is the same...
HTML/JS :
<!doctype html>
<html>
<head>
<title>User Identification</title>
<head>
<body>
<object id="MyClass" name="MyClass" type="application/x-shockwave-flash" data="MyClass.swf" width="1" height="1">
<param name="movie" value="MyClass.swf">
<embed src="MyClass.swf" width="1" height="1">
</object>
<script>
window.onload = function() {
var flash = document.getElementById("MyClass");
var test = flash.getStringJS("test");
alert(test); //pops up with "Hello World!" on Firefox
};
</script>
</body>
</html>
Does that help?

Related

Pass URL Parameter from Javascript to Flash Object in HTML

I have no HTML knowledge, I just have a simple task that I can't seem to grasp the concept of doing.
I want to take a url parameter and pass it to a swf object. I've figured out getting the parameter via javascript, but getting that return string to the object is my issue.
<!DOCTYPE html>
<html>
<body>
<script>
function myFunction() {
return "http://www.Twitch.tv/swflibs/TwitchPlayer.swf?channel=twitch";
}
</script>
Link Example
<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0" width="800" height="600" id="mymoviename">
<embed src="#" onload="this.src=myFunction()" quality="high" bgcolor="#ffffff"
width="800" height="600"
name="mymoviename" align="" type="application/x-shockwave-flash"
pluginspage="http://www.macromedia.com/go/getflashplayer">
</embed>
</object>
</body>
</html>
Markup based on Suggested answer(still does not work)
<!DOCTYPE html>
<html>
<body>
Link Example
<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0"
width="800" height="600" id="mymoviename">
<embed src="#" quality="high" bgcolor="#ffffff" width="800" height="600"
name="mymoviename" align="" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer">
</embed>
</object>
<script>
function myFunction() {
return "http://www.Twitch.tv/swflibs/TwitchPlayer.swf?channel=twitch";
}
document.getElementById('mymoviename').src = myFunction();
</script>
</body>
</html>
You can do it by following the following steps.
Move your <script> to just before </body>
And add the below code in <script>:
Code:
function myFunction() {
return "http://www.Twitch.tv/swflibs/TwitchPlayer.swf?channel=twitch";
}
document.getElementById('mymoviename').src = myFunction();
I found this article:
http://www.permadi.com/tutorial/flashVars/
Instead of passing the javascript variable to html markup, just write the markup with the script itself. Here is the working code:
<HTML><HEAD><TITLE>Example</TITLE></HEAD>
<BODY>
<SCRIPT LANGUAGE="JavaScript">
<!--
var myQueryString=document.location.search;
// remove the '?' sign if exists
if (myQueryString[0]='?')
{
myQueryString=myQueryString.substr(3, myQueryString.length-1);
}
document.write(
'<OBJECT classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://macromedia.com/cabs/swflash.cab#version=6,0,0,0" WIDTH="250" HEIGHT="250" id="flaMovie1"> <embed src="'+myQueryString+'" quality="high" bgcolor="#ffffff" width="800" height="600" name="mymoviename" align="" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer">\n'+
'</embed>\n'+
'</OBJECT>');
</SCRIPT>
</BODY>
</HTML>

Print PDF File in IFrame using javascript getting one page only

here is my code to print a pdf file. here while printing time iam getting one page only i need a solution for that
function printPdf(){
var ifr = document.getElementById("frame1");
//PDF is completely loaded. (.load() wasn't working properly with PDFs)
ifr.onreadystatechange = function () {
if (ifr.readyState == 'complete') {
ifr.contentWindow.focus();
ifr.contentWindow.print();
}
}
}
I suspect that's because the whole window gets printed (which has the current view of the iframe with the 1st page of the PDF rendered). Use <object> instead:
<!DOCTYPE html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<script>
function PrintPdf() {
idPrint.disabled = 0;
idPdf.Print();
}
function idPdf_onreadystatechange() {
if (idPdf.readyState === 4)
setTimeout(PrintPdf, 1000);
}
</script>
</head>
<body>
<button id="idPrint" disabled=1 onclick="PrintPdf()">Print</button>
<br>
<object id="idPdf" onreadystatechange="idPdf_onreadystatechange()"
width="300" height="400" type="application/pdf"
data="test.pdf?#view=Fit&scrollbar=0&toolbar=0&navpanes=0">
<span>PDF plugin is not available.</span>
</object>
</body>
This code is verified with IE. Other browsers will still render the PDF, but may not print it.
[UPDATE] If you need dynamic loading and printing, the changes to the above code are minimal:
<!DOCTYPE html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<script>
function PrintPdf() {
idPdf.Print();
}
function idPdf_onreadystatechange() {
if (idPdf.readyState === 4)
setTimeout(PrintPdf, 1000);
}
function LoadAndPrint(url)
{
idContainer.innerHTML =
'<object id="idPdf" onreadystatechange="idPdf_onreadystatechange()"'+
'width="300" height="400" type="application/pdf"' +
'data="' + url + '?#view=Fit&scrollbar=0&toolbar=0&navpanes=0">' +
'<span>PDF plugin is not available.</span>'+
'</object>';
}
</script>
</head>
<body>
<button id="idPrint" onclick="LoadAndPrint('http://localhost/example.pdf')">Load and Print</button>
<br>
<div id="idContainer"></div>
</body>
<iframe src="teste.pdf" id="meupdf" width="800" height="600" />
function printPdf) {
var PDF = document.getElementById("meupdf");
PDF.focus();
PDF.contentWindow.print();
}

How to detect when a Flash movie gets focus in Javascript code?

Is it possible to create a such event? If yes, how?
The markup for a flash movie is something like the next. Without changing ActionScript code of flash movie.
<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,29,0" width="32" height="32">
<param name="movie" value="file://test.swf">
<param name="quality" value="high">
<embed src="file://test.swf" quality="high" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash" width="32" height="32">
</embed>
</object>
Yes, you can do so in JavaScript.
First, it is a good idea to use swfobject to handle cross browser Flash issues. This is a JavaScript library to control SWF objects. You can download it here: https://code.google.com/p/swfobject/downloads/list
Basic Example:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<title>SWFObject - low level dynamic publishing example</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<script type="text/javascript" src="swfobject.js"></script>
<script type="text/javascript">
if (swfobject.hasFlashPlayerVersion("6.0.0")) {
var fn = function() {
var att = { data:"test.swf", width:"780", height:"400" };
var par = { flashvars:"foo=bar" };
var id = "replaceMe";
var myObject = swfobject.createSWF(att, par, id);
};
swfobject.addDomLoadEvent(fn);
}
</script>
</head>
<body>
<div id="replaceMe">Alternative content</div>
</body>
</html>
Next, just expand the example with an id inside the att variable like so:
var att = { data:"test.swf", width:"780", height:"400", id:"myId" };
You can access the object with getElementById() or a jQuery selector $("#myId")
Then attach an event to on focus like so:
JQuery: (recommended)
$('#myId').focus(function() {
alert('SWF is in focus');
});
or
Standard:
object.onfocus=function(){ alert('SWF is in focus'); }
You can place the player in a div, and select the div using javascipt. Also there is a more info here:
https://github.com/englandrp/Cross-browser-Flash-tabbing-and-focus-solution

Show random swf banners in HTML

I have two flash banners (.swf) and i want to show them randomly on page refresh.
I can do it with image files (using javascript), but with flash it's not working
For image files i can do this.
<script type='text/javascript'>
var HeaderImage= new Array()
HeaderImage[0]="URL-OF-HEADER-IMAGE-1";
HeaderImage[1]="URL-OF-HEADER-IMAGE-2";
var random=Math.round(2*Math.random());
document.write("<style>");
document.write("#header-wrapper {");
document.write(' background:url("' + HeaderImage[random] + '") no-repeat left TOP;');
document.write(" }");
document.write("</style>");
</script>
You can use SWFObject to embed the flash file and then randomly pick up the name of the file:
<script type="text/javascript" src="swfobject.js"></script>
<script type="text/javascript">
function getRandomFilename()
{
var names = ['myFile1.swf', 'myFile2.swf', 'myFile3.swf'];
var r = Math.floor(Math.random() * names.length);
return names[r];
}
var flashvars = {};
var params = {};
var attributes = {};
swfobject.embedSWF(getRandomFilename(), "myFlashContent", "800", "60", "9.0.0", false, flashvars, params, attributes);
</script>
</head>
<body>
<div id="myFlashContent">
</div>
</body>
If you can do it with image files, you can do it with flash. Embedding flash is a bit different, however, than with image files.
<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" width="550" height="400" id="movie_name" align="middle">
<param name="movie" value="movie_name.swf"/>
<!--[if !IE]>-->
<object type="application/x-shockwave-flash" data="movie_name.swf" width="550" height="400">
<param name="movie" value="movie_name.swf"/>
<!--<![endif]-->
<a href="http://www.adobe.com/go/getflash">
<img src="http://www.adobe.com/images/shared/download_buttons/get_flash_player.gif" alt="Get Adobe Flash player"/>
</a>
<!--[if !IE]>-->
</object>
<!--<![endif]-->
</object>
That is the embed code for flash apps. One alternative is you can use javascript to change the parameters in there. However, you could just as easily use iframes.
<iframe id="mov" src="movie.swf"></iframe>
Then, just use javascript to change the src value to the path to your flash movie.

Communication between javascript and Flash

I´ve already added:
ExternalInterface.addCallback('sendToActionScript', setKeyboardFocus);
ExternalInterface.call("setFocus", 'pathfinder');
inside the init() function of my main class.
In html I have this:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<title>pathFinder</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<style type="text/css" media="screen">
html, body { height:100%; background-color: #333333;}
body { margin:0; padding:0; overflow:hidden; }
#flashContent { width:100%; height:100%; }
</style>
<script type="text/javascript">
function getFlashMovie(movieName) {
var isIE = navigator.appName.indexOf("Microsoft") != -1;
return (isIE) ? window[movieName] : document[movieName];
}
function callToActionscript(str)
{
var fm = getFlashMovie("pathfinder");
fm.sendToActionScript(str);
}
function setFocus(id){
var f = document.getElementById(id);
f.focus();
callToActionscript('test')
}
</script>
</head>
<body>
<div id="flashContent" align='center'>
<table width="100%" height="100%" border="0" align="center" cellpadding="0"
cellspacing="0">
<tr>
<td align="center" valign="middle" bgcolor="#333333"><table width="1050" border="0"
cellpadding="0" cellspacing="0">
<tr>
<td>
<div align="center">
<OBJECT classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"
codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#versio
n=6,0,0,0"
WIDTH="1050"
HEIGHT="600"
id="pathfinder"
ALIGN="middle">
<PARAM NAME=movie VALUE="pathFinder.swf">
<PARAM NAME=quality VALUE=high>
<PARAM NAME=bgcolor VALUE=#333333>
<EMBED src="pathFinder.swf" quality=high bgcolor=#333333 WIDTH="1050" HEIGHT="600"
NAME="pathfinder" ALIGN="middle" TYPE="application/x-shockwave-flash"
PLUGINSPAGE="http://www.macromedia.com/go/getflashplayer" allowScriptAccess="always">
</EMBED> </OBJECT></div></td></tr></td></tr></table>
</div>
</body></html>
In the main stage I have a dynamic text field instance 'test_txt' to check if the function is called.
So after the ExternalInterface code I have:
private function setKeyboardFocus(str:String):void {
stage.addEventListener(KeyboardEvent.KEY_DOWN,checkKeysDown);
stage.addEventListener(KeyboardEvent.KEY_UP,checkKeysUp)
test_txt.text = str
}
The problem is flash doesn´t get keyboard focus ( the event listeneres of KeyboardEvent are never added ), the function setKeyboardFocus is never called.
Any help?
According to one source I found, you need to add allowScriptAccess="always" in two places.
Where you have it, in the <EMBED ... allowScriptAccess="always"> </EMBED> block.
You also need <PARAM NAME="allowScriptAccess" VALUE="always" > with the other PARAM blocks
Verify that fm is being assigned to the object or embed component. You should be able to verify this using the javascript debugging tools in Chrome or in Firefox. I think it's here where you're going wrong. This is a completely non-standard html wrapper from what I've seen myself but for the most part it appears you have things in order. One thing that is going to be wrong though is that the Object tag and information will be applied for IE, the Embed tag information will be applied for browsers that use the Netscape plugin (Firefox... well everything but IE). Also I'm not seeing an id on the Embed element, I think you need to also give this an ID like you did with the Object, I'm not sure if you'll get javascript errors if you use the same exact ID, I would probably call it pathFinderE or something like that then modify this method:
function getFlashMovie(movieName) {
var isIE = navigator.appName.indexOf("Microsoft") != -1;
return (isIE) ? window[movieName] : document[movieName + "E"];
}

Categories

Resources