Call an Adobe Flex/ActionScript method from JavaScript? - javascript

I need to know why JavaScript can't talk back to Flex.
I have a project that is going to use JavaScript to play a given video file. Its running on a custom MVC framework where asset files are loaded via the /static prefix.
Example: http://helloworld/static/swf/movie.swf`
I compile my Flex application using the mxmlc binary with options -static-link-runtime-shared-libraries=true, -use-network=true and --debug=true.
Flex
<?xml version="1.0" encoding="utf-8"?>
<s:Application
xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx"
creationComplete="init()">
<fx:Script>
<![CDATA[
import mx.controls.Alert;
import flash.external.ExternalInterface;
private function init():void {
log("Logging...");
if (ExternalInterface.available) {
ExternalInterface.call("HelloWorld.initFlash");
ExternalInterface.addCallback("playVideo", playVideo);
}
}
public function playVideo():void {
log("Playing video...");
}
public function log(message:String):void {
if (ExternalInterface.available) {
ExternalInterface.call(
"function log(msg){ if (window.console) { console.log(msg); } }",
message);
}
}
]]>
</fx:Script>
<s:Panel id="myPanel" title="Hello World" x="20" y="20">
<s:layout>
<s:HorizontalLayout
paddingLeft="10"
paddingRight="10"
paddingTop="10"
paddingBottom="10"
gap="5" />
</s:layout>
</s:Panel>
</s:Application>
HTML
<!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<title>Hello World</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/swfobject/2.2/swfobject.js"></script>
<script type="text/javascript">
$(function(){
var swfVersionStr = "10.1.0";
var xiSwfUrlStr = "playerProductInstall.swf";
var flashvars = {};
var params = {};
var attributes = {};
params.allowscriptaccess = "sameDomain";
params.quality = "high";
params.bgcolor = "#FFFFFF";
params.allowfullscreen = "true";
attributes.id = "HelloWorld";
attributes.name = "HelloWorld";
attributes.align = "left";
swfobject.embedSWF(
"HelloWorld.swf",
"flash-content",
"100%", "100%",
swfVersionStr, xiSwfUrlStr, flashvars, params, attributes );
HelloWorld = function(){
return {
initFlash : function() {
console.log("Called from Flex...");
console.log($("#HelloWorld").get(0).playVideo("be6336f9-280a-4b1f-a6bc-78246128259d"));
}
}
}();
});
</script>
<style type="text/css">
#flash-content-container {
width : 400px;
height : 300px;
}
</style>
</head>
<body>
<div id="layout">
<div id="header"><h1>Hello World</h1></div>
<div id="flash-content-container">
<div id="flash-content"></div>
</div>
</div>
</body>
</html>
Output
Logging...
Called from Flex...

I had the same issue, in the link provided by Chris Cashwell it shows the base for the solution.
Flex MXML
<?xml version="1.0" encoding="utf-8"?>
<s:Application
xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx"
creationComplete="init()">
<fx:Script>
<![CDATA[
import mx.controls.Alert;
import flash.external.ExternalInterface;
private function init():void {
consoleLog("Hello World");
try
{
Security.allowDomain("*"); //I need to add this.
ExternalInterface.marshallExceptions = true;
ExternalInterface.addCallback("sendAlert",sendAlert);
ExternalInterface.call("initCallBack");
} catch (error:Error) {
consoleLog("Error in ExternalInterface");
consoleLog("Error" + error.message);
}
}
public function sendAlert(s:String):void
{
Alert.show(s);
}
public function consoleLog(message:String):void {
if (ExternalInterface.available) {
ExternalInterface.call(
"function log(msg){ if (window.console) { console.log(msg); } }",
message);
}
}
]]>
</fx:Script>
<s:Panel id="panel1" title="Hello World" x="20" y="20">
<s:layout>
<s:HorizontalLayout
paddingLeft="10"
paddingRight="10"
paddingTop="10"
paddingBottom="10"
gap="5" />
</s:layout>
<s:TextArea id="textarea1"
width="300" height="100"
text="Hello World" />
</s:Panel>
</s:Application>
HTML
<!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<title>Hello World</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/swfobject/2.2/swfobject.js"></script>
<script type="text/javascript">
var flexApp;
function initCallBack() {
flexApp = document.getElementById("HelloWorldFlex");
if (flexApp != undefined) {
try {
flexApp.sendAlert( "Hello World" );
} catch(err) {
console.log("There was an error on the flex callback.");
console.log(err);
}
} else {
console.log("The flex object does not exist yet");
}
return;
}
$(function(){
HelloWorld = function(){
return {
init : function() {
var swfVersionStr = "10.1.0";
var xiSwfUrlStr = "playerProductInstall.swf";
var flashvars = {
bridgeName : "flex",
};
var params = {};
var attributes = {};
params.allowscriptaccess = "always";
params.quality = "high";
params.bgcolor = "#FFFFFF";
params.allowfullscreen = "true";
attributes.id = "HelloWorldFlex";
attributes.name = "HelloWorldFlex";
attributes.align = "left";
swfobject.embedSWF(
"HelloWorld.swf",
"flash-content",
"100%", "100%",
swfVersionStr, xiSwfUrlStr, flashvars, params, attributes );
}
}
}();
HelloWorld.init();
});
</script>
<style type="text/css">
#flash-content-container {
width : 400px;
height : 300px;
}
</style>
</head>
<body>
<div id="layout">
<div id="header"><h1>Hello World</h1></div>
<div id="flash-content-container">
<div id="flash-content"></div>
</div>
</div>
</body>
I tested it on Flex 4.1, please notice that i had to add the bin-debug folder (C:\flexworkspaces\project\bin-debug) to the flash security app ( http://www.macromedia.com/support/documentation/en/flashplayer/help/settings_manager04.htmlconfiguration ) Please notice that this internet URL is in fact an app that modifies the Flex local configuration.
The logs can be displayed in the Firebug console.

Decided to go with FABridge. For others heres a working example.
MXML
<?xml version="1.0" encoding="utf-8"?>
<s:Application
xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx"
xmlns:bridge="bridge.*"
creationComplete="init()">
<fx:Declarations>
<bridge:FABridge bridgeName="flex" />
</fx:Declarations>
<fx:Script>
<![CDATA[
import mx.controls.Alert;
import flash.external.ExternalInterface;
private function init():void {
consoleLog("Hello World");
}
public function sendAlert(s:String):void
{
Alert.show(s);
}
public function consoleLog(message:String):void {
if (ExternalInterface.available) {
ExternalInterface.call(
"function log(msg){ if (window.console) { console.log(msg); } }",
message);
}
}
]]>
</fx:Script>
<s:Panel id="panel1" title="Hello World" x="20" y="20">
<s:layout>
<s:HorizontalLayout
paddingLeft="10"
paddingRight="10"
paddingTop="10"
paddingBottom="10"
gap="5" />
</s:layout>
<s:TextArea id="textarea1"
width="300" height="100"
text="Hello World" />
</s:Panel>
</s:Application>
HTML
<!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<title>Hello World</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/swfobject/2.2/swfobject.js"></script>
<script type="text/javascript" src="bridge/FABridge.js"></script>
<script type="text/javascript">
var flexApp;
var initCallback = function() {
flexApp = FABridge.flex.root();
var textarea1 = flexApp.getTextarea1();
textarea1.setText( "Hello World (Updated)" );
flexApp.sendAlert( "Hello World" );
return;
}
$(function(){
HelloWorld = function(){
return {
init : function() {
var swfVersionStr = "10.1.0";
var xiSwfUrlStr = "playerProductInstall.swf";
var flashvars = {
bridgeName : "flex",
};
var params = {};
var attributes = {};
params.allowscriptaccess = "sameDomain";
params.quality = "high";
params.bgcolor = "#FFFFFF";
params.allowfullscreen = "true";
attributes.id = "HelloWorld";
attributes.name = "HelloWorld";
attributes.align = "left";
swfobject.embedSWF(
"HelloWorld.swf",
"flash-content",
"100%", "100%",
swfVersionStr, xiSwfUrlStr, flashvars, params, attributes );
FABridge.addInitializationCallback( "flex", initCallback );
}
}
}();
HelloWorld.init();
});
</script>
<style type="text/css">
#flash-content-container {
width : 400px;
height : 300px;
}
</style>
</head>
<body>
<div id="layout">
<div id="header"><h1>Hello World</h1></div>
<div id="flash-content-container">
<div id="flash-content"></div>
</div>
</div>
</body>
</html>

Related

Why does it says my browser not supporting?

I'm using Visual studio code for programming and I'm testing my codes with live server. But today I'm stuck with an error.
My code is below.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=,, initial-scale=1.0">
<title>Test lesson</title>
<script src="/JS/jquery-3.6.1.min.js"></script>
<link rel="stylesheet" type="text/css" href="css/main.css"/>
<script>
$(function(){
$("div").find("*").css({
"color":"red",
"border":"2px solid red",
});
});
</script>
</head>
<body class="ancestors">
<div class="descendants" style="width:500px;">div
<p class="first">P (child)
<span>Span (grandchild)</span>
</p>
<p class="second">P (child)
<span>Span (grandchild)</span>
</p>
</div>
</body>
</html>
So, when i run this code with live server, my browser says :
// <![CDATA[ <-- For SVG support if ('WebSocket' in window) { (function () { function refreshCSS() { var sheets = [].slice.call(document.getElementsByTagName("link")); var head = document.getElementsByTagName("head")[0]; for (var i = 0; i < sheets.length; ++i) { var elem = sheets[i]; var parent = elem.parentElement || head; parent.removeChild(elem); var rel = elem.rel; if (elem.href && typeof rel != "string" || rel.length == 0 || rel.toLowerCase() == "stylesheet") { var url = elem.href.replace(/(&|\?)_cacheOverride=\d+/, ''); elem.href = url + (url.indexOf('?') >= 0 ? '&' : '?') + '_cacheOverride=' + (new Date().valueOf()); } parent.appendChild(elem); } } var protocol = window.location.protocol === 'http:' ? 'ws://' : 'wss://'; var address = protocol + window.location.host + window.location.pathname + '/ws'; var socket = new WebSocket(address); socket.onmessage = function (msg) { if (msg.data == 'reload') window.location.reload(); else if (msg.data == 'refreshcss') refreshCSS(); }; if (sessionStorage && !sessionStorage.getItem('IsThisFirstTime_Log_From_LiveServer')) { console.log('Live reload enabled.'); sessionStorage.setItem('IsThisFirstTime_Log_From_LiveServer', true); } })(); } else { console.error('Upgrade your browser. This Browser is NOT supported WebSocket for Live-Reloading.'); } // ]]>
Can anyone help me please for fix that error?

Webcam Image Update in Javascript

I am having major brain ache on this one. I have a webcam that i snap an image from every 5 seconds. I have read all of the comments and I can successfully display an image from the webcam but cannot get the image to update. I have read the similar posts and tried everything.
Am i missing something?
This is what I have:
<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<title>Webcam</title>
<script type="text/javascript">
var x = 0;
function init() {
window.onmessage = (event) => {
if (event.data) {
var ImageURL = document.getElementById("webcam1");
ImageURL.src = event.data;
Clear();
function Clear() {
document.getElementById("Load").style.display = "None";
document.getElementById("Test").innerHTML = "Clearing";
setInterval(UpdateImage, 20000);
function UpdateImage() {
x = x + 1;
var temp = ImageURL.src;
UpdatedImageURL.src = temp + "?=t" + new Date().getTime();
var UpdatedImageURL = document.getElementById("webcam1");
document.getElementById("Test").innerHTML =
"Updating .... " + x;
}
}
}
}
}
</script>
</head>
<body onload="init();">
<p id="Load">Loading ....</p>
<p id="Test">Starting ....</p>
<img id="webcam1" alt=" " width="700" height="450" />
</body>
</html>

how we can capture nanorep response?

I have integrated the nanorep in my html page.
I have created the account at nanorep website.
when i am asking question it is responding answer well.
I am able to plug in nanorep correctly.
Now I want a functionality that on any button click event I want the answered which is provided by nanorep.
Thanks in advanced.
Here is the following code I have written for this.
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<title></title>
<script type="text/javascript" language="javascript">
var _nRepData = _nRepData || []; _nRepData['kb'] = '19583554';
function nanorep() {
_nRepData['embed'] = { account: 'etech', container: 'Mydiv2', width: 400, maxHeight: 320, dynamicSize: true, cdcFrame: '', cdcVersion: 3, scriptVersion: '3.12.2.3' };
(function () {
var windowLoadFunc = function () {
var _nRepData = window._nRepData || [];
_nRepData['windowLoaded'] = true;
if (typeof (_nRepData['windowOnload']) === 'function') {
_nRepData['windowOnload']();
// alert(window._nRepData.toString());
}
};
if (window.attachEvent)
window.attachEvent('onload', windowLoadFunc);
else if (window.addEventListener)
window.addEventListener('load', windowLoadFunc, false);
var sc = document.createElement('script'); sc.type = 'text/javascript';
sc.async = true; sc.defer = true; sc.src = ('https:' == document.location.protocol ? 'https://' : 'http://') + 'my.nanorep.com/widget/scripts/embed.js?account= etech';
var _head = document.getElementsByTagName('head')[0]; _head.appendChild(sc);
var a = document.getElementById('hdn').value = "hiddenvalue";
//alert(a);
})();
}
function answer1() {
alert("answer value" + $('#hdn').val());
}
function btngo_onclick() {
if (document.getElementById('hdn').value == 'hiddenvalue') {
answer1();
}
else {
alert("not working");
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div id="Mydiv2">
</div>
<asp:HiddenField runat="server" ID="hdn" />
</form>
<button id="btngo" onclick="return btngo_onclick()"> GO </button>
</body>
</html>

Updating local dom won't reflect shady dom

In x-num.html
<link rel="import" href="../polymer/polymer.html">
<dom-module id="x-num">
<style></style>
<template>
<span id="number"></span>
</template>
</dom-module>
<script>
Polymer({
is: "x-num",
properties: {
type: String,
value: 'normal'
},
attached: function() {
var contentNode = Polymer.dom(this).childNodes[0];
var number = Number(contentNode.textContent);
var result = "";
switch(this.type){
case "simplified":
if(number > 1000)
result = number / 1000 + "K+";
else
result = number;
break;
case "comma":
result = number.toLocaleString('en-IN');
break;
case "normal":
default:
result = number;
break;
}
this.$.number.textContent = result;
},
detached: function(){
console.log("detached");
},
attributeChanged: function(name, type){
console.log("attribute Changed: "+name);
}
});
</script>
In index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script>Polymer = {dom: 'shadow'};</script>
<title>Testing Polymer Element</title>
<script src="webcomponentsjs/webcomponents-lite.js"></script>
<link rel="import" href="x-num.html">
</head>
<body>
<x-num>3546</x-num>
<br/>
<x-num type="comma">3546</x-num>
<br/>
<x-num type="simplified">3546</x-num>
</body>
</html>
When I try to do document.querySelector("x-num").innerHTML = "4000", it still shows 3546, I would like to ask if there is anyway to make the result change when the content changes
If I add this setNumber function to x-num.html
<script>
Polymer({
...,
setNumber: function(number) {
this.$.number.textContent = number;
}
});
I can change each line to "4000" with this in index.html:
...
<script>
var list = document.getElementsByTagName('x-num');
for (i = 0; i < list.length; i++)
list[i].setNumber(4000);
</script>
</body>
I'm using Polymer 0.9-rc.1

backup streaming with jwplayer

I use this js to create a jwplayer.
<script language="javascript" type="text/javascript" src="embed/swfobject.js"></script>
<div id="playerContainer">player should load here</div>
<script language="javascript" type="text/javascript">
var flashvars = {};
flashvars.linkfromdisplay = "true";
flashvars.autostart = "true";
flashvars.height = "480";
flashvars.width = "640";
flashvars.volume = "90";
flashvars.repeat = "false";
flashvars.displayheight = "640";
flashvars.displaywidth = "480";
flashvars.skin = "embed/minimal.zip";
flashvars.stretching = "exactfit";
flashvars.file = "http://" +
escape("1.1.1.1/stream.php");
var params = {};
params.menu = "true";
params.allowscriptaccess = "always";
params.allowfullscreen = "true";
params.wmode = "transparent";
var attributes = {};
attributes.id = "playerContainer";
attributes.wmode = "transparent";
attributes.name = "playerContainer";
swfobject.embedSWF("jwplayer/player.swf",
"playerContainer", "640", "480", "8","expressInstall.swf", flashvars,
params, attributes);
</script>
This works fine but when there is any problem and the stream is down or not found, I want to stream another link.
You can use onError() to do this.
Here is a demo:
http://support.jwplayer.com/customer/portal/articles/1442607-example-a-custom-error-message
Code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Displaying a Custom Error Message</title>
<link rel="icon" type="image/x-icon" href="http://www.jwplayer.com/wp-content/themes/jwplayer-105/favicon.ico">
<script type='text/javascript' src='http://p.jwpcdn.com/6/8/jwplayer.js'></script>
<style type="text/css">
body {
margin: 0; padding: 0
}
</style>
</head>
<body>
<div id="container"></div>
<script>
jwplayer("container").setup({
file: "rtmp://fms.12E5.edgecastcdn.net/0012E5/videos/Qvxp3Jnv-68183.flv",
//file: "rtmp://fml.12E5.edgecastcdn.net/3012E5/tuxcast",
image: "http://s.jwpcdn.com/thumbs/RxiqSWej-640.jpg"
});
jwplayer().onError(function(){
jwplayer().load({file:"http://content.jwplatform.com/videos/7RtXk3vl-52qL9xLP.mp4",image:"http://content.jwplatform.com/thumbs/7RtXk3vl-480.jpg"});
jwplayer().play();
});
jwplayer().onComplete(function(){
window.location = window.location.href;
});
jwplayer().onBuffer(function(){
theTimeout = setTimeout(function(){
jwplayer().load({file:"http://content.jwplatform.com/videos/7RtXk3vl-52qL9xLP.mp4",image:"http://content.jwplatform.com/thumbs/7RtXk3vl-480.jpg"});
jwplayer().play();
},5000);
});
jwplayer().onPlay(function(){
clearTimeout(theTimeout);
});
</script>
</body>
</html>

Categories