How to get the swf object from within a web page? - javascript

Suppose the swf file is embeded into the page with the following code:
<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" id="myFlash" width="600" height="500">
<param name="movie" value="myMovie.swf">
<embed type="application/x-shockwave-flash" src="myMovie.swf" name="myFlash" width="600" height="500" >
</embed>
</object>
What are the ways to get a reference to the movie with the help of JavaScript?

function getMovie(movieName) {
if (navigator.appName.indexOf("Microsoft") != -1) {
return window[movieName];
} else {
return document[movieName];
}
}
var flash = getMovie('myFlash')

Does...
var myReference = document.getElementById("myFlash");
... suit your needs? What do you aim to do with this reference once you are done?

This is the shortest answer I can write:
var swf = this["mySWF"];

It's easy, but you need to be weary of Internet Explorer
var myFlash = $.browser.msie ? window[ 'myFlash' ] : document[ 'myFlash' ];

Related

Get attribute of embed element and changes values in flashvars Javascript?

How can I get the value of flashvars attribute?
<embed src="http://wl2static.lsl.com/common/flash/as3/MemberApplet026.swf"
id="opera_elb" width="100%"
height="100%"
allowscriptaccess="always"
allowfullscreen="true"
bgcolor="ffe8ef"
quality="high"
pluginspage="http://www.macromedia.com/go/getflashplayer"
type="application/x-shockwave-flash"
flashvars="muteaudio=0&ishd=1&ishq=0&twoway=0&proxyip=">
I am using getElementsByTagName to get the element.
var Em = content.document.getElementsByTagName('embed');
And replace values in flashvars
<script>
function myFunction()
{
var Em = content.document.getElementsByTagName('embed');
var str = Em[0].getAttribute('flashvars').innerHTML;
var res = str.replace("muteaudio=0","muteaudio=1");
document.getElementsByTagName("embed").innerHTML=res;
}
</script>
But when I try error: Uncaught ReferenceError: content is not defined
please help me.
Okay so here is a solution (strictly to change the attribute of flashvars!). First I think you have a few syntax errors within your JS. So I modified it and here is the JS:
function myFunction()
{
var Em = document.getElementById('vid');
var str = Em.getAttribute('flashvars');
var contentSpot = document.getElementById("he");
contentSpot.innerHTML = Em.getAttribute('flashvars');
Em.setAttribute('flashvars', 'muteaudio=1')
// contentSpot.innerHTML = Em.getAttribute('flashvars');/* I used this to see if the change occurred.*/
}
window.onload = myFunction();
So contentSpot is a div element I created to observe the change.
the html is here:
<embed id="vid" src="http://wl2static.lsl.com/common/flash/as3/MemberApplet026.swf"
id="opera_elb" width="100%"
height="100%"
allowscriptaccess="always"
allowfullscreen="true"
bgcolor="ffe8ef"
quality="high"
pluginspage="http://www.macromedia.com/go/getflashplayer"
type="application/x-shockwave-flash"
flashvars="muteaudio=0&ishd=1&ishq=0&twoway=0&proxyip=">
<div id="he"> Hello</div> <!-- The created div to observe -->
Okay so here is my suggestion:
1)pop in the cleaned up code into a jsfiddle, then observe the content.
2)Then remove the line: contentSpot.innerHTML = Em.getAttribute('flashvars'); above the code: Em.setAttribute('flashvars', 'muteaudio=1').
3) remove comments slashes and then hit ctrl + enter to observe the attribute change.
*really watch your "."/DOM syntax and case sensitivity.
Hope this helps you out!

Modify XML RSS Feed for Windows 8 using JavaScript

Currently making a Windows 8 RSS reader app for a specific site. Everything is working except for video [usually YouTube] since the website uses <object></object> to embed videos rather than <iframe>. the result is just a large blank object block where ever the video should be.
My first instinct was to find and replace the <object></object> tags with <iframe> and add the src attribute with the proper URL. I created a dummy app to test if this method would work, and the solution worked, if all you were changing was static HTML.
Dummy App Code:
<body>
<div style="text-align: center;">
<object width="853" height="480" id="test">
<param name="movie" value="http://www.youtube.com/v/2rDs7W3WRIk?version=3&hl=en_US"></param>
<param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param>
<embed src="http://www.youtube.com/v/2rDs7W3WRIk?version=3&hl=en_US" type="application/x-shockwave-flash" width="853" height="480" allowscriptaccess="always" allowfullscreen="true"></embed>
</object></div>
Wrote and called the below function, which does indeed work. Want to do something similar to the XML document:
function setHTML5video() {
var listOfSrcs = document.getElementsByTagName("embed");
for (var i = 0; i < listOfSrcs.length; i += 1) {
var videoSrc = document.getElementsByTagName("embed")[i].getAttribute("src");
var newSrc = videoSrc.replace("/v/", "/embed/");
//var newNode = '<iframe width="853" height="480" src="' + newSrc + '" frameborder="0" allowfullscreen></iframe>';
var iFrame = document.createElement("iframe");
iFrame.setAttribute("src", newSrc);
document.getElementsByTagName("object")[i].replaceNode(iFrame);
//WinJS.Utilities.setOuterHTMLUnsafe(test, newNode);
}
}
End of Dummy App Code.
However, due to lack of knowledge of the Windows 8 API and despite searching all day for the answer online, I cannot find how to do the same to an XML feed that is being downloaded from an external site. I am probably missing something fundamental.
function itemInvoked(z) {
var currentArticle = articlesList.getAt(z.detail.itemIndex);
WinJS.Utilities.setInnerHTMLUnsafe(articlecontent, currentArticle.content);
articlelist.style.display = "none";
articlecontent.style.display = "";
mainTitle.innerHTML = currentArticle.title;
WinJS.UI.Animation.enterPage(articlecontent);
}
When the user clicks on a thumbnail, the XML RSS feed for that corresponding article is pulled up and injected into the with the id = "articlecontent". I want to modify that feed prior to injecting it.
<section id="content">
<div id="articlelist" data-win-control="WinJS.UI.ListView"
data-win-options="{ itemDataSource: mmoNewsPosts.ItemList.dataSource, itemTemplate: MMOItemTemplate }"></div>
<!-- Article Content -->
<div id="articlecontent"></div>
<!-- Article Content -->
</section>
Edit, because there appears to be confusion, I already have the feed loaded in via WinJS.xhr:
function downloadMMOFeed(FeedUrl) {
WinJS.xhr({ url: FeedUrl, responseType: "xml" }).then(function (rss) {
pageTitle = rss.responseXML.querySelector("title").textContent;
mainTitle.innerHTML = pageTitle;
var items = rss.responseXML.querySelectorAll("item");
//more stuff...
for (var n = 0; n < items.length; n +=1) {
article.content = items[n].querySelector("description").textContent;
//more stuff...
Could you not just load the XML feed in by XHR and then parse the result before binding it to the page? For Example:
WinJS.xhr({
url: "http://www.w3schools.com/xml/note.xml", responseType: "xml"
})
.done(
function (request) {
var text = request.responseText;
//TODO : Parse the XML returned by the server which is in var text
});
In Windows 8 there is no cross domain restriction so something like this is entirely possible.

Why won't this JS RegExp work?

I have a list of YouTube videos on a page and I want to use JS to grab a list of the src URLs from each <embed> tag and use them to append thumbnail images elsewhere on the page.
To do this, I need to grab the Video ID from the YouTube URL using a RegExp, but it refuses to work, even though the RegExp appears to work when I test it here: http://www.regular-expressions.info/javascriptexample.html
Here's the code I have:
**Here is the JSBin page to see it all in action: http://jsbin.com/uvoya3/23/edit
var addImages = function () {
var features = document.getElementById('features'),
embeds = features.getElementsByTagName('embed'),
ids = [], i, thumbNav, items, mysrc, pattern, ytid, newImg, matchArray;
for (i = 0; i < embeds.length; i += 1) {
mysrc = embeds[i].getAttribute('src');
pattern = /^(http:\/\/www.youtube.com\/v\/)([a-zA-Z0-9]*)(\?[^\?]*)$/;
ytid = mysrc.replace(pattern, '$2');
alert("src number " + i + " is " + ytid);
ids.push(ytid);
}
};
window.onload = addImages;
The alert is there to test what the RegExp is finding, and each time it pushes the whole mysrc string because it's not matching at all. The mysrc values are
http://www.youtube.com/v/jfiNQGFVjb4?fs=1&hl=en_US
http://www.youtube.com/v/qtzjzMsJiO8?fs=1&hl=en_US
http://www.youtube.com/v/baa-dGj2LhQ?fs=1&hl=en_US
which are being pulled from this HTML
<ul id="features">
<li><object width="480" height="385"><param name="movie" value="http://www.youtube.com/v/jfiNQGFVjb4?fs=1&hl=en_US"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/jfiNQGFVjb4?fs=1&hl=en_US" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="480" height="385"></embed></object></li>
<li><object width="480" height="385"><param name="movie" value="http://www.youtube.com/v/qtzjzMsJiO8?fs=1&hl=en_US"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/qtzjzMsJiO8?fs=1&hl=en_US" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="480" height="385"></embed></object></li>
<li><object width="640" height="385"><param name="movie" value="http://www.youtube.com/v/baa-dGj2LhQ?fs=1&hl=en_US"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/baa-dGj2LhQ?fs=1&hl=en_US" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="640" height="385"></embed></object></li>
</ul>
Does anyone see why my RegExp or my JS is off track here?
**PS Here is the JSBin URL http://jsbin.com/uvoya3/23/edit
It's working fine, except for the third one, because that one contains a -. And by the way, _ may be supported as well.
So, a better regular expression would be: /^(http:\/\/www.youtube.com\/v\/)([a-zA-Z0-9-_]*)(\?[^\?]*)$/.
On my Javascript console this works fine:
> "http://www.youtube.com/v/baa-dGj2LhQ?fs=1&hl=en_US".replace(/^(http:\/\/www.youtube.com\/v\/)([a-zA-Z0-9-_]*)(\?[^\?]*)$/, '$2');
< "baa-dGj2LhQ"
You could optimize your code by the way:
var addImages = function () {
// Part 1
var features = document.getElementById('features'),
embeds = features.getElementsByTagName('embed'),
pattern = /^(http:\/\/www.youtube.com\/v\/)([a-zA-Z0-9-_]*)(\?[^\?]*)$/,
ids = [], i, thumbNav, items, mysrc, ytid, newImg;
for (i = 0; i < embeds.length; i++) {
ids[i] = embeds[i].src.replace(pattern, '$2');
}
...

Flash External Interface issue with Firefox

I am having a hard time getting ExternalInterface to work on Firefox. I am trying to call a AS3 function from javascript. The SWF is setup with the right callbacks and it is working in IE.
I am using AC_RunActiveContent.js to embed the swf into my page. However, I have modified it to add an ID to the Object / Embed Tags. Below are object and embed tag that are generated for IE and for Firefox respectively.
<object codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0" width="400" height="400" align="middle" id="jpeg_encoder2" name="jpeg_encoder3" classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" >
<param name="movie" value="/jpeg_encoder/jpeg_encoder3.swf" />
<param name="quality" value="high" />
<param name="play" value="true" />
<param name="loop" value="true" />
<param name="scale" value="showall" />
<param name="wmode" value="window" />
<param name="devicefont" value="false" />
<param name="bgcolor" value="#ffffff" />
<param name="menu" value="false" />
<param name="allowFullScreen" value="false" />
<param name="allowScriptAccess" value="always" />
</object>
<embed
width="400"
height="400"
src="/jpeg_encoder/jpeg_encoder3.swf"
quality="high"
pluginspage="http://www.macromedia.com/go/getflashplayer"
align="middle"
play="true"
loop="true"
scale="showall"
wmode="window"
devicefont="false"
id="jpeg_encoder2"
bgcolor="#ffffff"
name="jpeg_encoder3"
menu="false"
allowFullScreen="false"
allowScriptAccess="always"
type="application/x-shockwave-flash" >
</embed>
I am calling the function like this...
<script>
try {
document.getElementById('jpeg_encoder2').processImage(z);
} catch (e) { alert(e.message); }
</script>
In Firefox, I get an error saying "document.getElementById("jpeg_encoder2").processImage is not a function"
Any Ideas?
Hmm, did you expose your actionscript function to Javascript with addCallback ?
Adobe documentation on addCallback
Below is an example of how a Flash movie is placed within a html page. This movie is very simple movie with a stop action at the beginning. The movie is shown below under Test Runs subject. This particular html code was auto generated by FlashMX's Publish command. Notice that the Flash movie file is simplemovie.swf; and an id and a name have been assigned automatically by Flash to match the movie filename (minus the .swf extension). In reality, the name and id could be anything (but do not use exoteric names, especially, do not start with a number), as long as it has not been used by any other element in the same page.
`codebase="http://download.macromedia.com/pub/shockwave/cabs/flash`/swflash.cab#version=6,0,0,0"
` WIDTH="150" HEIGHT="75" id="simplemovie" ALIGN="">
` quality=medium
` swliveconnect="true"
` bgcolor=#FFFFFF WIDTH="150" HEIGHT="75"
` name="simplemovie"
` ALIGN=""
`TYPE="application/x-shockwave-flash"
` PLUGINSPAGE="http://www.macromedia.com/go/getflashplayer">
there is a play function in the flash file the following function will calls that function:
function testEval(stringToEval)
{
var movie=eval(stringToEval);
if (movie)
{
if (movie.PercentLoaded())
{
if (movie.PercentLoaded()==100)
{
movie.Play();
}
else
{
alert("movie is still loading, try again soon");
}
}
else
{
alert("movie object found-but unable to send command");
}
}
else
{
alert("movie object not found");
}
}
See this post.
You want a JS function more like this to retrieve the Flash object (rather than getElemById):
function thisMovie(movieName) {
if(navigator.appName.indexOf("Microsoft") != -1) {
return window[movieName];
} else {
return document[movieName];
}
};
And make sure not to call this function until the document is loaded.
Try having the same id in both object and embed tags. I remember one browser is using one tag and another browser the other...don't know which one is which. I had the same issue some time ago.
I'm got around by modifying the Example Code that comes with flash. Making sure it works, then stripping it down and adapting it for my use.
In the example notice that the object tag the id set to "ExternalInterfaceExample", then the embed tag has the name parameter set to "ExternalInterfaceExample" as well. I think that might be your clue.
Good luck!
Are your swf's visible (on the page) before you try calling them? If not, read this: swf-not-initializing-until-visible
Try these two things:
First, try calling the function from Javascript like this:
var swf;
if(navigator.appName.indexOf("Microsoft") != -1) {
swf = window["jpeg_encoder2"];
} else {
swf = document["jpeg_encoder2"];
}
if(typeof(swf) == "undefined") swf = document.getElementById("jpeg_encoder2");
swf.processImage(z);
Second, I've found that ExternalInterface calls in Firefox seem to only work with embed tags, not object tags. See if you can get it to work if you just use an embed tag. (Right now, I'm not clear whether the HTML/Javascript combo you've posted will access the object or the embed element.)
If instead of using AC_RunActiveContent.js to embed your flash movie you use swfobject there is a easy build-in way of doing that.
<head>
<script type="text/javascript" src="swfobject.js"></script>
<script type="text/javascript">
try {
swfobject.getObjectById('jpeg_encoder2').processImage(z);
} catch (e) { alert(e.message); }
</script>
</head>
If you are not using swfObject you could just copy and paste swfobject.getObjectById straight in to your code:
<script type="text/javascript">
function getObjectById(objectIdStr) {
var r = null;
var o = getElementById(objectIdStr);
if (o && o.nodeName == "OBJECT") {
if (typeof o.SetVariable != UNDEF) {
r = o;
}
else {
var n = o.getElementsByTagName(OBJECT)[0];
if (n) {
r = n;
}
}
}
return r;
getObjectById('jpeg_encoder2').processImage(z); //call your method
</script>

Problem with NetStream.pause() in ActionScript called from Javascript

I am working on a very simple player written in MXML+ActionScript whose functions are exported to be called by a simple Javascript in an HTML page.
Both codes are provided below.
For the mp3 "path" all is working perfectly for playing, pausing, resuming and stopping...
For the m4a "path", starting is working well, stopping too but pausing is bugging
After having started an m4a, when I clicked on "pause" it rightly stops the stream.
But when I am clicking back on the button to resume, it does not start again at all
Does anybody know where is the problem?
Is the fact that I'm using just a simple Apache Web Server and not a real Flash Streaming server the reason why it does not work?
Thanks in advance for your help.
The MXML+ActionScript 3
<?xml version="1.0"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" creationComplete="callBacks()">
<mx:Script>
<![CDATA[
import flash.events.Event;
import flash.media.Sound;
import flash.net.URLRequest;
import flash.external.ExternalInterface;
public var playingChannel:SoundChannel;
public var playingSound:Sound;
public var pausePosition:int=0;
public var playingUrl:String="";
public var codec:String="";
public var playingStream:NetStream;
public function playSound(url:String):void {
if (playingUrl!=url) {
if (playingUrl!="") {
stopSound();
}
playingUrl=url;
codec=playingUrl.substring(playingUrl.length-3);
if (codec=="m4a") {
var mySound:SoundTransform;
var connect_nc:NetConnection = new NetConnection();
connect_nc.connect(null);
playingStream=new NetStream(connect_nc);
playingStream.play(url);
}
else if (codec=="mp3") {
playingSound=new Sound(new URLRequest(url));
playingChannel=playingSound.play();
}
}
else {
if (codec=="m4a")
playingStream.pause();
else
playingChannel=playingSound.play(pausePosition);
}
}
public function pauseSound():void {
if (codec=="m4a")
playingStream.pause();
else if (codec=="mp3") {
pausePosition=playingChannel.position;
playingChannel.stop();
}
}
public function stopSound():void {
if (codec=="m4a")
playingStream.close();
else if (codec=="mp3") {
pausePosition=0;
playingChannel.stop();
}
playingUrl="";
}
public function callBacks():void {
ExternalInterface.addCallback("play",playSound);
ExternalInterface.addCallback("pause",pauseSound);
ExternalInterface.addCallback("stop",stopSound);
}
]]>
</mx:Script>
</mx:Application>
and the basic HTML+Javascript
<html>
<head>
<script src='jquery.js'></script>
<script>
function play() {
//alert('clicked');
var url=$("#url").val();
var k=url.substring(url.length-3);
fromFlash('testFlash').play(url);
var b=document.getElementById('pp');
b.setAttribute('src','pauseButton.jpg');
b.setAttribute('onclick','pause()');
}
function pause() {
fromFlash('testFlash').pause();
var b=document.getElementById('pp');
b.setAttribute('src','playButton.jpg');
b.setAttribute('onclick','play()');
}
function stop() {
fromFlash('testFlash').stop();
var b=document.getElementById('pp');
b.setAttribute('src','playButton.jpg');
b.setAttribute('onclick','play()');
}
function fromFlash(movieName) {
var isIE = navigator.appName.indexOf("Microsoft") != -1;
return (isIE) ? window[movieName] : document[movieName];
}
</script>
</head>
<body>
<object id="testFlash" width="0" height="0">
<param name="movie" value="player.swf"></param>
<param name="allowFullScreen" value="true"></param>
<embed name="testFlash" src="player.swf" type="application/x-shockwave-flash" allowfullscreen="true" width="0" height="0">
</embed>
</object>
<input id="url"/>
<span><img id="pp" src="playButton.jpg" onclick="play()"/></span>
<span><img src="stopButton.jpg" onclick="stop()"/></span>
</body>
</html>
I believe you want to call pause() again to resume, not play().
According to the NetStream documentation, the pause() method is used for both pause and resume.

Categories

Resources