external interface - javascript

I have a calc function in java script that takes three integer parameters,
following is the AS3 code
import flash.external.ExternalInterface;
var para:Array = new Array();
send_btn.addEventListener(MouseEvent.CLICK, clickListener);
function clickListener(eventObj:Object ):void {
para.push(mean.text);
para.push(std.text);
para.push(points.text);
trace("click > " + para);
ExternalInterface.call("calc",para );
}
is this the right way of doing it and how do i get back 3 arguments back from the javascript and display them in flash?

In addition, you need to register your AS function so that it's available to the container:
ExternalInterface.addCallback("callFlash", myASFunction);
Then, from your container (JS), you call the AS function and pass whatever parameters you want to it.
<script language="JavaScript">
flashObject.callFlash(param1, param2, param3);
</script>
...
<object id="flashObject"...>
...
<embed name="flashObject".../>
</object>
Lastly, in AS3, you write the function that will be executed when the container "calls back":
function myASFunction(param1:String,param2:String,param3:String):void {
trace("\n Received call from JS: " + param1 + param2 + param3);
}

Related

Cannot access javascript function in ADF InlineFrame

I have a jsff page containing af:InlineFrame.
The source of this InlineFrame is HTML file say Frame.html
This html file has a javascript function called inlineframeFunction()
I have a button added in the jsff page.
My usecase is to invoke the function inlineframeFunction on click of the button which i am not able achieve.
var doc = inlineFrame.contentDocument?
inlineFrame.contentDocument: inlineFrame.contentWindow.document;
doc.frameFunction();
Frame.html
<script type="javascript">
function inlineframeFunction(){
alert('Inline Frame Function ');
}
</script>
JSFF Page
<af:panelGroupLayout id="pgl1" layout="vertical">
<af:resource type="javascript">
function inlineFrameRegionPageFunction() {
alert('Region Page Function');
var inlineFrame = document.getElementById('r1:0:if2');
var doc = inlineFrame.contentDocument? inlineFrame.contentDocument: inlineFrame.contentWindow.document;
doc.frameFunction();
}
</af:resource>
</af:panelGroupLayout>
<af:panelGroupLayout id="pgl2" layout="vertical">
<af:panelBox text="Inline Frame Region" id="pb2"
inlineStyle="background-color:Lime; border-color:Lime;">
<f:facet name="toolbar"/>
<af:inlineFrame id="if2" source="/Frame.html" shortDesc="InlineFrame"
inlineStyle="background-color:Gray;"/>
<af:commandButton text="Inline Region Button" id="rb2"
actionListener="#{pageFlowScope.RegionBean.onClickInlineFrameRgnButton}"/>
</af:panelBox>
</af:panelGroupLayout>
I used the following and it worked!
function inlineFrameRegionPageFunction() {
var frameComp =$('[id*="InlineFrame"]', document)[0].id;
document.getElementById(frameComp).contentWindow.frameFunction();
}
</af:resource>
To execute a javascript from a managed bean in adf you can use the following function (https://cedricleruth.com/how-to-execute-client-javascript-in-an-adf-java-bean-action/) :
/*** In YOURJSF.jsf button, or other component that need to execute a javascript on action, add : ****/
<af:commandButton text="ClickMe" id="cb1" actionListener="#{YOURSCOPE.YOURJAVABEAN.clickToExecuteJavascriptAction}"/>
/*** In YOURJAVABEAN.java class add : ***/
public void clickToExecuteJavascriptAction(ActionEvent actionEvent) {
this.executeClientJavascript("console.log('You just clicked : " + actionEvent.getSource() + " ')");
//Note: if you use a java string value in this function you should escape it to avoid breaking the javascript.
//Like this : stringValue.replaceAll("[^\\p{L}\\p{Z}]", " ")
}
//You should put this function in a util java class if you want to use it in multiple bean
public static void executeClientJavascript(String script) {
FacesContext facesContext = FacesContext.getCurrentInstance();
ExtendedRenderKitService service = Service.getRenderKitService(facesContext, ExtendedRenderKitService.class);
service.addScript(facesContext, script);
}
Then in your case, refer to this question to call your iframe js function using javascript inside your action listener (Calling javascript function in iframe)
document.getElementById("if2").contentWindow.inlineframeFunction();

Activate javascript string onload on code behind C#

Good day!
I need a help on activating my javascript function via on-load on code behind.
Here is my code:
string script = #"var applyCss = function () {
var css = '#CalendarPanel1-month-day-20170607, #CalendarPanel1-month-day-20170614 {background-color: #D0D3D4;}';
Ext.net.ResourceMgr.registerCssClass('someCssClassId', css);
}; ";
ScriptManager.RegisterClientScriptBlock(this, typeof(Page), "css", script, true);
By the way, my code above works in front-end via button click.
But my desired result is, I want my javascript function to work on page load without needing to click the button. I put my javascript function in code-behind because I will put dynamic dates in the css variables. The code above still has static variables. (CalendarPanel1-month-day-20170607)
Will gladly appreaciate any response / solution. Big thanks!
You could use an immediately invoked function to do the trick. Basically you don't give a name to your javascript function and you invoke it right after it's defined.
For example:
var script = #"(function () {alert('Hello');})(); ";
ScriptManager.RegisterStartupScript(this, typeof(Page), "123", script, true);
You need to wrap the function with its body between parenthesis then another set of parenthesis to invoke the function.
You can also pass parameters to your function (which I'm assuming it's what you want to do):
var myAlertText = "Hello Hello";
var script = #"(function (myText) {alert(myText);})('" + myAlertText + "');" ;
If I were you though I would defined the function in client code and just invoke it from code behind with the right parameters.
An alternative and fancier way to call javascript code from code behind would be using X.Call(). Check out this example:
<%# Page Language="C#" %>
<!DOCTYPE html>
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
if (!X.IsAjaxRequest)
{
string script = #"var myJSSideVar = 'my var value';
var applyCss = function (paramOne, paramTwo) {
var css = '#CalendarPanel1-month-day-20170607, #CalendarPanel1-month-day-20170614 {background-color: #D0D3D4;}';
Ext.net.ResourceMgr.registerCssClass('someCssClassId', css);
Ext.Msg.alert('applyCss called.', 'I\'ve been run with parameters: (' + paramOne + ', ' + paramTwo + ').');
};";
var hi = "hello";
X.AddScript(script);
X.Call("applyCss", new object[] { hi, new JRawValue("myJSSideVar") });
}
}
</script>
<html>
<head runat="server">
<title></title>
</head>
<body>
<form runat="server" id="form1">
<div>
<ext:ResourceManager runat="server" />
</div>
</form>
</body>
</html>
Notice the second parameter sent to the script call is sent "raw", i.e., it calls: applyCss("hello", myJSSideVar)
If you need to pass but one single parameter you don't need to pass an array, e.g. X.Call("applyCss", hi);

Pass a parameter to existing onClick JS function

Very basic question, but how can I add/populate a parameter to the onClick function of an HTML element?
<a onClick="someFunction()" id="testLink">Some function</a>
//PSEUDO CODE
var someFunctionParam = document.getElementById('testLink');
someFunctionParam.addParameter(someParam);
Obviously "addParameter" isn't a valid method in Javascript, can anyone guide on how to do so?
The best way in my opinion is to rewrite you JS to something like this:
<a onclick="aNewFunction()" id="testLink">Some function</a>
function aNewFunction() {
// Invoke your existing function here;
someFunction();
//PSEUDO CODE
var someFunctionParam = document.getElementById('testLink');
someFunctionParam.addParameter(someParam);
}
Best way I would think of is
$(function () {
var parameter='Joe Root';
var functionName = $('#testLink').attr("onclick");
$('#testLink').attr("onclick",
functionName.replace('()', "('" + parameter + "')"));
alert($('#testLink').attr("onclick"));
});
function someFunction(name) {
alert("Hi " + name);
}
As, you can see, this works http://jsfiddle.net/hXpSN/1/

Calling a function inside a svg file on a object tag from javascript

In my HTML page I got :
<script language="JavaScript">
function mostrar(blo) {
var str = "";
...
window.document.tbl27svg.pinta(str);
}
And in some place in the same html page I have:
<object id="tbl27svg" data="../../imagenes/svg/tbl27.svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="1100px" height="1000px" type="image/svg+xml"/>
And in the file tbl27.svg I need to call a function:
parent.pinta=pinta
function inicia(event){
SVGDocument = event.target.ownerDocument;
}
function pinta(strSVG){
var nuevoNodo=parseXML(strSVG, document);
if(document.getElementById('grafico1').childNodes.length>0){
if(!document.getElementById('grafico2').childNodes.length>0)
SVGDocument.getElementById("grafico2").appendChild(nuevoNodo);
}else{
SVGDocument.getElementById("grafico1").appendChild(nuevoNodo);
}
}
So, I have tried several ways to call pinta() function on tbl27.svg file. But always I got a java script error:
"Object doesn’t support this property or method"
Be sure to place pinta() function declaration before window.document.tbl27svg.pinta(str);:
<script>
function pinta(){
...
}
function mostrar(blo) {
var str = "";
...
window.document.tbl27svg.pinta(str);
}
</script>

why call flash function from javascript work but FileReference don't work in flash?

I need call flash function from javascript. I use flash.external and addCallback to do this. all things work well but when I use FileReference in my flash, function did not open my browser ...
please see below describtion:
I call my function in javascript with this code:
<input type="button" value="Browse" onclick="sendToFlash('Hello World! from HTML');" />
you can see all my HTML as below:
<html>
<head>
<title>Upload test</title>
</head>
<script>
function hello (size) {
alert ("size hast: " + size);
}
function sendToFlash(val){
var flash = getFlashObject();
flash.new_browser(val);
}
var flash_ID = "Movie2";
var flash_Obj = null;
function getFlashObject(){
if (flash_Obj == null){
var flashObj;
if (navigator.appName.indexOf( "Microsoft" ) != -1){
flashObj = window[flash_ID];
}
else{
flashObj = window.document[flash_ID];
}
flash_Obj = flashObj;
}
return flash_Obj;
}
</script>
<body>
<center>
<embed width="560" height="410" type="application/x-shockwave-flash"
flashvars="sampleVars=loading vars from HTML"
salign="" allowscriptaccess="sameDomain" allowfullscreen="false" menu="true" name="Movie2"
bgcolor="#ffffff" devicefont="false" wmode="window" scale="showall" loop="true" play="true"
pluginspage="http://www.adobe.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash"
quality="high" src="Movie2.swf">
</center>
<input type="button" value="Browse" onclick="sendToFlash('Hello World! from HTML');" />
</body>
</html>
when I click Browse in html page, javascript call sendToFlash function and SendToFlash function send my string (Hello World! from HTML) to flash.
in flash I get this string with below code:
resultsTxtField.text = "";
uploadButton.onPress = function () {
return browse_file("Hello World! from Flash");
}
import flash.external.*;
ExternalInterface.addCallback("new_browser", this, browse_file);
function browse_file (my_test_val) {
_root.resultsTxtField.text = "val: " + my_test_val;
import flash.net.FileReference;
var fileTypes:Array = new Array();
var imageTypes:Object = new Object();
imageTypes.description = "Images (*.jpg, *.jpeg, *.gif, *.png)";
imageTypes.extension = "*.jpg; *.jpeg; *.gif; *.png";
fileTypes.push(imageTypes);
var fileListener:Object = new Object();
var btnListener:Object = new Object();
var fileRef:FileReference = new FileReference();
fileRef.addListener(fileListener);
fileRef.browse(fileTypes);
fileListener.onCancel = function(file:FileReference):Void
{
_root.resultsTxtField.text += "File Upload Cancelled\n";
}
fileListener.onSelect = function(file:FileReference):Void
{
_root.resultsTxtField.text += "File Selected: " + file.name + " file size: "+ file.size + " file type: " + file.type;
getURL("javascript:hello("+file.size+");");
}
}
I have only one Scene and this code is on root of this Scene. and I have one movie clip named uploadButton and has only a rectangle that work as button in this sample.
when you click on rectangle browse_file("Hello World! from Flash"); called and a browser open that you can select a photo to upload.
when you click on browse in html same process must do but as you see variable send to function but browser to select a photo did not open any more.
I try several ways. for example I set new function to open only picture browser or set new Scene or use gotoAndPlay and more but there is another problem.
you can download my source from below link:
http://www.4shared.com/zip/YTB8uJKE/flash_uploader.html
note that javascript onclick="sendToFlash('Hello World! from HTML');" don't work in direct opening. you must open it in localhost.
I'll be so so happy for any clue.
thanks so much
Reza Amya
You can't programmatically call browse(), it has to be from a mouse click inside Flash: http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/net/FileReference.html#browse()
In Flash Player 10 and Flash Player 9 Update 5, you can only call
this method successfully in response to a user event (for example, in
an event handler for a mouse click or keypress event). Otherwise,
calling this method results in Flash Player throwing an Error
exception.
after a day reading I know that it is impossible for security reasons.
then you can't open file reference with addCallback javascript code any way. for more information read fileReference browse from js, simulate keypress in flash workaround
Thanks again
Reza Amya

Categories

Resources