externalinterface - calling javascript from SWF - apache-flex

HI,
im trying to call a javascript function from my actionscript code but its not working;
as3:
if (ExternalInterface.available)
{
try
{
ExternalInterface.addCallback("changeDocumentTitle",null);
}
catch(error:Error)
js (inside velocity file using swfobject)
function changeDocumentTitle()
{
alert('call from SWF');
}
anyone know what could be happenin?

If you are trying to invoke a JS function from within your Flex app, you want to use ExternalInterface.call(...) and not ExternalInterface.addCallback(...). From the docs:
public static function call(functionName:String, ... arguments):*
Calls a function exposed by the Flash Player container, passing zero or more arguments. If the function is not available, the call returns null; otherwise it returns the value provided by the function. Recursion is not permitted on Opera or Netscape browsers; on these browsers a recursive call produces a null response. (Recursion is supported on Internet Explorer and Firefox browsers.)
If the container is an HTML page, this method invokes a JavaScript function in a script element.
http://livedocs.adobe.com/flex/3/langref/flash/external/ExternalInterface.html
addCallback() is used if you want to expose an ActionScript function from your Flash app to the HTML container so that it can be invoked via JavaScript.

On the local system, communication between the SWF and Javascript tends to be hampered by security issues. You can reconfigure your flash to allow some of these communications via the "settings manager".
It may also be an issue with "allowscriptacces" not being set where you embed the flash object.
Another problem may be that flash tries to call javascript before the javascript is loaded. The init order thing can be quite annoying.

Related

Unable to override OnApplyTemplate

I'm trying to override the NavigationView behavior:
public partial class CustomizableNavigationView : NavigationView
{
public CustomizableNavigationView()
{
// This gets called
}
protected override void OnApplyTemplate()
{
// This doesn't
}
}
It works on UWP, but not on Android. On Android, it doesn't call OnApplyTemplate and the screen remains blank, there's not content. Questions:
Why doesn't OnApplyTemplate get called on Android? I see that here: https://platform.uno/docs/articles/implemented/windows-ui-xaml-frameworkelement.html it says OnApplyTemplate() is on all platforms
There's no error or anything displayed in the Output panne in VS while running with debugger. Should there be any in this case? Do I need to enable something to log errors?
I noticed that if I don't use partial it gaves me error saying partial is required. This is required only on Android, why is that? A more in-depth explanation would help a lot to understand how things work.
Once I figure out why OnApplyTemplate is not called, I want to do this:
base.OnApplyTemplate();
var settingsItem = (NavigationViewItem)GetTemplateChild("SettingsNavPaneItem");
settingsItem.Content = "Custom text";
My hunch is this won't work on Android. Am I correct? :)
Jerome's answer explains why OnApplyTemplate() was not getting called, to address your other questions:
You can configure logging filters for Uno, this is normally defined in App.xaml.cs. Warnings should be logged by default.
The partial is required because Uno does some code-gen behind the scenes to create plumbing methods used by the Xamarin runtime. Specifically because the control is ultimately inheriting from ViewGroup on Android, it's a native object, and requires special constructors that are used only by Xamarin's interop layer. There's some documentation in progress on this.
Try it and see. :) GetTemplateChild() is supported, and setting ContentControl.Content in this way is supported, so I would expect it to work.
At current version (1.45 and below), the application of styles is behaving differently from UWP. We're keeping track of this in this issue.
The gist of the issue is that Uno resolves the style using the current type and not DefaultStyleKey, and cannot find an implicit style for CustomizableNavigationView.
A workaround for this is to either create a named style from the default NavigationView style, or create an implicit style that uses CustomizableNavigationView as the TargetType instead of NavigationView.

How can I inject JavaScript file into a WebEngineView page?

I'm adding a script tag to a web page once it's fully loaded in a WebEngineView, but it's silently failing somehow.
I inject the script by invoking webview.runJavaScript with this code:
var s = document.createElement('script');
s.src = "qrc:/jquery-2.1.4.min.js";
document.body.appendChild(s);
That's perfectly standard and to a certain extent it works as expected, i.e., if I view the html source of the page, the script tag has indeed been appended to the body.
The problem is that the script isn't being downloaded, or isn't being evaluated, or something. All I know is in the above example the jQuery functions aren't available. If I load a small JavaScript test file with one global variable, that variable's not available either. Changing the url to http instead of qrc and pointing it to a web server makes no difference.
Injecting an img tag works fine; the image is loaded and displayed.
But JavaScript is broken somehow. Does anyone know how to fix this?
The problem had to do with the asynchronous nature of QML and JavaScript.
I was inserting a script tag to inject jQuery, and then I was calling a function to de-conflict my inserted version of jQuery from whatever version of jQuery might already be in the original page.
But I believe the webview had not finished parsing the inserted jQuery library before my de-conflicting function was called, so it failed. (I'm not very experienced with browser programming or I might have suspected this from the beginning.)
The solution was to insert a script tag with a small bit of JavaScript that inserts jQuery and then sets a timeout to wait 200ms before calling the de-conflict function. Like so:
function insertAuhJQuery(){
var s = document.createElement("script");
s.src = "qrc:/jquery-2.1.4.min.js";
document.body.appendChild(s);
window.setTimeout(deConflictJQuery, 200);
}
function deConflictJQuery(){
auh = {};
auh.$ = jQuery.noConflict(true);
}
insertAuhJQuery()
That works reliably and is acceptable for my purpose.

Swing applet JDialog result to wicket page

I call an applet contained html from wicket page, based on the applet's JDialaog confirmation, I need to get back to wicket page, If user does not confirm he needs to stay in applet only.
I know setResponsePage in wicket can invoke the html but it needs to be directed only when user confirms from applets jdialog. any ideas please..basically need to invoke wicket page from applet, i tried to set the param in applet URL but somehow my getAppetContext() is returning null.
You have several options. I think the nicest will be using ajax.
The design will be as follows:
WicketPage
-- javascript
-- java-applet
You have an AbstractAjaxBehaviour that renders javascript, that in turn renders your Java applet.
You pass on the behavhiour's getCallbackUrl() to the javascript function. This can be done in the renderHead() of the AbstractAjaxBehaviour usign a response.render( OnDomReadyHeaderItem.forScript( js ) );
You can call javascript from your Applet. So when the confirmation has taken place, the applet will call some javascript function, which in turn call a Wicket.ajax.get.
This Wicket.ajax.get can use the callbackUrl from the behaviour, and you end up in the server-side Java again, in the body on the onRequest of the AjaxBehaviour
See also these references:
https://docs.oracle.com/javase/tutorial/deployment/applet/invokingJavaScriptFromApplet.html
http://wickedsource.org/2013/01/07/rolling-your-own-ajax-behavior-with-wicket/
http://wicket.apache.org/guide/guide/ajax.html
try {
if(appletCtx != null){
camera.endLiveView();
camera.closeSession();
CanonCamera.close();
getAppletContext().showDocument(new URL(LOCAL_URI+"?wicket:bookmarkablePage=%3Acom.xyz.app.tla.wickola.page.takingViewingPictures.UploadEmployeePhotoPage"),"_parent");
System.exit( 0 ); // a separate jvm for my photo applet
}
} catch (MalformedURLException e) {
e.printStackTrace();
}

Javascript-Caching Video Player

I've got the following Javascript for creating the HTML of video player. I use Javascript because this is the only way I can tell the player which video to play.
function createPlayer(videoSource){
document.writeln("<div id=\"player\">");
document.writeln("<object width=\"489\" height=\"414\" >");
document.writeln("<param name=\"player\" value=\"bin-debug/FlexPlayer.swf\">");
//etc
The problem is FlexPlayer.swf is loading every time and I need to cache this SWF file. Maybe I should use Javascript constructor but don't know how in this case. Any code help will be greatly appreciated.
If you're video player is in flex (and I'm guessing that it is with the flex tag and the bin-debug folder) - you should just call into the flex app in order to set the video.
You can allow flex and javascript to communicate with each other, without having to embed different versions of it in the HTML! It's awesome, check it out...
In your flex app, after it is initialized you can add something like this :
ExternalInterface.addCallback( 'playVideoFromJS' , playVideo );
What the above does is expose a function named "playVideoFromJS" that can be called in your javascript that will execute the 'playVideo' funciton in the flex app! Neat!
Then add a function like so somewhere in your flex app:
public function playVideo ( videoToPlay : String ) : void {
...play video code here
}
Then in javascript, you can actually call your flex function playVideo!
myFlexAppName.playVideoFromJS( 'myvideoofile.flv' );
More information on ExternalInterface here :
http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/external/ExternalInterface.html?filter_flash=cs5&filter_flashplayer=10.2&filter_air=2.6#addCallback()

How do I unload a externally loaded SWF file from a SWFLoader component in Adobe Flex?

I have an application that loads external SWF files and plays them inside a Adobe Flex / Air application via the SWFLoader Flex component. I have been trying to find a way to unload them from a button click event. I have Google'd far and wide and no one seems to have been able to do it without a hack. The combination of code I see people use is:
swfLoader.source = ""; // Removes the external link to the SWF.
swfLoader.load(null); // Forces the loader to try to load nothing.
// Note: At this point sound from the SWF is still playing, and
// seems to still be playing in memory.
flash.media.SoundMixer.stopAll();
// Stops the sound. This works on my development machine, but not
// on the client's.
If the SWFs are closed (hidden) this way, eventually the program crashes.
Any ideas? I have found tons of posts in various forums with people having the same problem. I assume I will get one wrong/incomplete answer here, and than my post will sink into nothingness as usual, but either way, thanks in advance!
Edit 1: I can't edit the actual SWF movies, they're created by the client. If I can't close any SWF opened through Flex, isn't that a problem with the Flex architecture? Is my only option sending the SWFs to the web browser?
... isn't that a problem with the Flex architecture?
Yes it is, and it also affects Flash in general. Until you can take advantage of the Loader.unloadAndStop() method in FP10 (AIR 1.5), you can't guarantee that externally loaded content will not continue to consume memory and cpu resources, even if you use the Loader.unload() method. (To be honest, I'm not 100% sure that even that will guarantee freeing of resources, but maybe I'm a pessimist.)
The next best thing is for you to insist that the creators of the content you load adhere to a set of guidelines, including exposing something like a dispose() method which your app can call to ask it to release as many resources as possible before you unload() it. If this isn't possible, then your application will almost definitely bloat in memory and cpu usage each time you load an external swf. Sorry.
If it makes you feel any better, you're not alone. ;)
It is a problem that a badly created SWF can sink your application, and many of the issues with this will be fixed in Flash Player 10, as others have mentioned. However, regardless of platform you will always risk having problems if you load third party code, there's always the possibility that it contains bugs, memory leaks or downright malicious code. Unless you can load content into a sandbox (and you can't in Flash, at least not yet), loading bad things will sink your app, it's as simple as that.
I'm sorry to say that unless you can guarantee the quality of the loaded content you can't guarantee the quality of your own application. Flash developers are notorious for writing things that leak, or can't be unloaded, because Flash makes it easy to do the wrong thing, especially for things that live on the time line. Loading any Flash content that you don't have control over directly is very perilous.
The best solution is
swfLoader.autoLoad = false;
swfLoader.unloadAndStop();
swfLoader.autoLoad = true;
In this way you stop the player, unload the content from memory and avoid the sound to remain playing..
Cheers
The problem resides in the loaded swf, it simply does not clean up the audio after itself.
Try attaching an unload event onto movieclips like this:
MovieClip(event.target.content).loaderInfo.addEventListener(Event.UNLOAD, unloadMovieClipHandler);
private function unloadMovieClipHandler(event:Event) : void
{
SoundMixer.stopAll();
}
I'd generally stay away from SWFLoader and use the classes in the mx.modules package.
Flex has a module system that enables this type of behavior. You can check it out here : http://livedocs.adobe.com/flex/3/html/help.html?content=modular_3.html . In general, dynamically loading and unloading swf components is tricky, especially if those modules modify any global state in the application (styles, etc..). But if you create an interface for your modules, and then each class you load/unload implement that interface as well as extend the flex module class, you can load and unload them cleanly.
Try the following:
try {
new LocalConnection().connect('foo');
new LocalConnection().connect('foo');
} catch (e:*) {}
That will force a Garbage Collection routine. If your SWF is still attached, then you've missed some sort of connection, like the audio.
There are a couple ways to force GC, which all kind of suck because they spike CPU, but the good news is that an official way is coming in Flash Player 10:
unloadAndStop
link: http://www.gskinner.com/blog/archives/2008/07/unloadandstop_i.html
Until then, I'm afraid you'll have to force it with hacks like I showed above.
You have not shown all of your code so I am going to assume you didn't use the unload method of the Loader class. Also swfLoader.load(null) seems wrong to me as the load method is expecting a URLRequest object. When you want to clean things up at the end, set the object's value to null instead of calling a null load. The fact that your still hearing audio indicates that your data wasn't unloaded, or the audio file does not reside inside the content that was unloaded. Lets walk through this.
Example below
var loader:Loader = new Loader();
var request:URLRequest = new URLRequest('test.swf');
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onSwfLoad, false, 0, true);
function onSwfLoad(e:Event):void
{
addChild(loader);
loader.contentLoaderInfo.addEventListener(Event.UNLOAD, onLoaderUnload, false, 0, true);
loader.contentLoaderInfo.removeEventListener(Event.COMPLETE, onSwfLoad, false);
}
function onLoaderUnload(e:Event):void
{
trace('LOADER WAS SUCCESSFULLY UNLOADED.');
}
//Now to remove this with the click of a button, assuming the buttons name is button_mc
button_mc.addEventListener(MouseEvent.MOUSE_DOWN, onButtonDown, false, 0, true);
function onButtonDown(e:MouseEvent):void
{
loader.unload();
loader.contentLoaderInfo.removeEventListener(Event.UNLOAD, onLoaderUnload);
//When you want to remove things completely from memory you simply set their value to null.
loader = null;
button_mc.removeEventListener(MouseEvent.MOUSE_DOWN, onButtonDown);
}
I do hope that this was helpful, and I am sorry if it was redundant, but without seeing your code I have no way of knowing exactly how you approached this.

Resources