Flex BlazeDS detect browser close - spring

I have a Flex application that connects to a BlazeDS server using the StreamingAMF channel. I want to detect on the server side in case the browser is closed. I have added an implementation for FlexClientListener & registered it to the FlexClient (FlexContext.getFlexClient().addClientDestroyedListener)
But the clientDestroyed method of Listener is not invoked on browser close. It gets invoked on Session timeout. Is there any other way to achieve this?

You won't be able to detect browser interactions on a client from the server.
Your best guess is to make use of ExternalInterface. It allows your Flash app to communicate with JavaScript, and vice versa.
Use the JavaScript onClose event to trigger some JavaScript which will call a function in your Flash App which will make a remote call to let your server side know that the browser is being closed.

We too had similar issue, not closing the session was causing memory leak in BlazeDS, We wrote the below script in swf wrapper javascript, to make ensure that closing browser invokes session closure code in flex
<script language="JavaScript" type="text/javascript">
function cleanup()
{
getMyApplication("swf_filename_without_extension").cleanUp();
alert("Disconnected! Press OK to continue.");
}
function getMyApplication(appName)
{
if (navigator.appName.indexOf ("Microsoft") != -1)
{
return window[appName];
}
else
{
return document[appName];
}
}
</script>
<body onbeforeunload="cleanup()">
In Flex add a call back on creation complete listener
ExternalInterface.addCallback("cleanUp",cleanUp);
and write all your session closure code in cleanUp method.
Note: don't forget to put the alert message in javascript. That will give enough time for cleanUp method to execute.

Related

OneSignal registration fails after refresh

I am using OneSignal in my Laravel/Vue app. I have included it within <head> as stated in documentation:
<script src="https://cdn.onesignal.com/sdks/OneSignalSDK.js" async=""></script>
<script>
var OneSignal = window.OneSignal || [];
OneSignal.push(function() {
OneSignal.init({
appId: "{{ env('ONESIGNAL_APP_ID') }}"
});
OneSignal.showNativePrompt();
});
</script>
<script>
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/OneSignalSDKWorker.js')
.then(function () {
console.log('Service worker registered');
})
.catch(function (error) {
console.log('Service worker registration failed:', error);
});
} else {
console.log('Service workers are not supported.');
}
</script>
I also have a service worker of my own, so I've followed the documentation here as well.
What is happening after a hard reset is that service worker gets installed and it is all fine, however once I refresh the page I am getting:
OneSignalPageSDKES6.js?v=151102:1 Uncaught (in promise) InvalidStateError: The current environment does not support this operation.
at Function.getServiceWorkerHref (https://cdn.onesignal.com/sdks/OneSignalPageSDKES6.js?v=151102:1:41510)
at xe. (https://cdn.onesignal.com/sdks/OneSignalPageSDKES6.js?v=151102:1:144028)
at Generator.next ()
at r (https://cdn.onesignal.com/sdks/OneSignalPageSDKES6.js?v=151102:1:716)
And I have no idea what does that mean? What is "current environment"? Where to start debugging? I've tried putting console logs around it, however it led me nowhere...
You would start debugging by looking at the source code of the library.
In your case your library is the OneSignal SDK for browsers.
Let's do this!!!
We can see that this error is thrown by getServiceWorkerHref function (which is defined here) and the error message is driven by the InvalidStateReason enumeration:
case InvalidStateReason.UnsupportedEnvironment:
super(`The current environment does not support this operation.`);
break;
If you look at the first linked file, you will see the note on getServiceWorkerHref OneSignal developers left for the those who dare venture into their source code:
else if (workerState === ServiceWorkerActiveState.Bypassed) {
/*
if the page is hard refreshed bypassing the cache, no service worker
will control the page.
It doesn't matter if we try to reinstall an existing worker; still no
service worker will control the page after installation.
*/
throw new InvalidStateError(InvalidStateReason.UnsupportedEnvironment);
}
As you can see, the error is raised when the service worker has the "Bypassed" state. What is that, you may ask? Let's look at ServiceWorkerActiveState enumeration below, in the same file:
/**
* A service worker is active but not controlling the page. This can occur if
* the page is hard-refreshed bypassing the cache, which also bypasses service
* workers.
*/
Bypassed = 'Bypassed',
It seems, when the browser "hard-refreshes" the page, it bypasses the service worker and OneSignal can't properly initialize when that happens. Hard-refresh can happen for a number of reasons — here are some of them (to the best of my knowledge):
if you click the refresh button a bunch of times (usually seconds consecutive refresh within a short period of time may trigger this)
if you have caching disabled in your DevTools
if the server sets a no-cache header
What is happening after a hard reset
I don't know exactly what you mean by "hard reset", but that sounds like it would trigger this issue. I would suggest you close your browser and then visit the page you are working on without using "reset" functions — theoretically, the service worker should be used for caching on consecutive visits and that would ensure OneSignal can function.

Socket.IO client event handler not called?

I'm an iOS developer who recently started using Socket.IO. During the life cycle of my iOS application, my server will be receiving messages from my app as the client, but for one particular case, the server will also need to receive a message from a web browser as the client. I'm testing a very basic browser UI, which includes a text field and a button and on the tap of that button, a numeric code (which was entered in the text field) needs to be sent to the server. This is what that looks like:
<form>
Code:<br>
<input type="text" id="code" name="code"><br>
<input type="submit" id="validatebutton" value="Validate">
<script src="/socket.io-client/dist/socket.io.js"></script>
<script>
document.getElementById("validatebutton").onclick = function() {
var socket = io('http://localhost:3000');
socket.on('connect', function(clientSocket) {
clientSocket.emit('validateCode', document.getElementById("code"));
});
};
</script>
</form>
The connection works fine. When I run this code, the client successfully connects to the listening socket server. The only problem is that the event handler is not executed. I may be very off here, but what I went for is a client event handler, which is included in the Swift SDK:
self.socket.on(clientEvent: .connect, callback: { (data:[Any], ack:SocketAckEmitter) in
// Do something here
})
self.socket.connect()
I'm just assuming that the Javascript client has a client event handler (named 'connect') as well, which is received by the client at the moment of connecting to a server. Like I said, I may be way off here. I'm just following the Socket.IO documentation posted on their website, which tells me to do it this way. If someone can tell me what I'm missing, or what I'm doing wrong, it would be much appreciated. Sorry for all the noobishness, but I really don't know where else to turn, since the official documentation is very vague and the other question on Stack are a little too advanced for me.
I wouldn't put the emit function inside the connect. Try emitting like below in your client
<script>
var socket = io('http://localhost:3000');
document.getElementById("validatebutton").onclick = function() {
socket.emit('validateCode', document.getElementById("code"));
};
</script>
Your click event was probably getting executed, but the emit was not due to it being wrapped in the connect function (which only gets executed when the socket connects to the server)
Also I would put the JavaScript in its own file, but for now, at least after the form (not inside it) will work.

Railo Custom 505 handler and ajax pathing

I have an external javascript file that calls a setinterval function that checks a cfc for file transfer completion between server and a remote computer. When I call this function with standard error handler it works. Soon as I add the custom error handler it fails. Im dumb founded.
File_transfer.js
{
Function check_stream_server ()
Ajax call to query, application scoped, query-object.
Path = "ss_check.cfc"
};
// exception log and response with custom error
// I work with no custom error handler
Function send_file ()
{
Ajax to Put file in object; // I work
Same ajax call to Start stream.
thread if not running; //I work
Setinterval (check_stream_server, 5000) //I set interval
}
}
}
Index.cfm null {
Include the file_transfer.js
<button>click </button>
<script>
Button.on ('click', function (){
Send_file()
})
</script>
}
Index.cfm, check_ss.cfc, and the object_insert.cfc are all in same folder. Js is in external lib folder.
Sorry that this code sucks but I'm typing this from phone and won't be able to sleep tonight or be dreaming about it all night.
If it helps I'm also running a compiled archive.
It was a bug in setting the cf admin on update error. There was a remote clients = arrayofclients that was not removed from someone copying and pasting the example in the docs. I had a work around that worked by initializing the functions into the proper scopes in the initial cfm page, but later found out it was a bug when setting the custom error handler

Load async YouTube API in to ReactJS application

I need to load the YouTube JavaScript API which requires you to include a script tag with an onload query string which points towards a global callback function. Once the Google client is loaded the callback gets called:
<script>
function init() {
gapi.client.setApiKey('465723722VeAji1ZVqYiJxB7oyMTVLI');
gapi.client.load('youtube', 'v3', function() {
YouTubeClientLoaded = true;
});
}
</script>
<script src="https://apis.google.com/js/client.js?onload=init"></script>
This all works fine in principle but I'm having a hard time working out how to integrate this global callback in to my ReactJS application. How can I tell react that the client is loaded and ready to use?
I've had a few thoughts but all seem hacky. I thought about starting the React app up and setting a timer that periodically checks for the existence of the YouTubeClientLoaded global variable (or the gapi object) or perhaps a pubsub mechanism so my global init function can emit when it's ready. Problem with the pubsub route is that the pubsub itself would also need to be global so then how do I get that communicating with React...
Is there a more correct way of achieving this?

Websocket message interupts dynamic loading of ExtJS class

in my ExtJS 4.1 application I use a websocket connection to remotely insantiate and control ExtJS classes from the server. The client is registered to websocket.onmessage and is waiting for incoming commands.
I defined a simple protocol for that. The server sends a "CREATE classname id". On client side I use Ext.create to instantiate the class. The server then can send commands via the websocket to the object. E.g. "DOSTUFF id". I'm using the dynamic loading mechnism of ExtJS.
In Chrome everything works fine.
The problem with Firefox is, that the second command message (DOSTUFF) is executed BEFORE the object has been created. This leads to an error because the object cannot be found. It seems that the second websocket commandmessage is executed before ExtJS has loaded the file via HTTP-GET.
In my world JavaScript is executed sequentially (I don't use webworkers). I think the call of Ext.create(..) should be executed synchronously with the HTTP-GET in background, shouldn't it?
Here is a "pseudo" trace output of my client application:
ExecuteCommand (Enter): CREATE ("MyClass", "1")
HTTP-GET "MyClass.js"
ExecuteCommand (Enter): DOSTUFF ("1")
ExecuteCommand (Error): DOSTUFF ("1"): Object not found
ExecuteCommand (Enter): CREATE ("MyClass", "1"): OK! Object created!
It makes sense. The GET request is async by default see Firefox doc: https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest/Synchronous_and_Asynchronous_Requests
To avoid this issue check for object existence and if need be let the server know to resend in a few seconds, and repeat.
Ok, as mentioned by DmitryB the HTTP-GET works asynchronous. After the XMLHttpRequest is sent, the control is passed to the next websocket.onmessage.
I solved this problem by using Ext.require with a callback function before I call Ext.create.
It looks something like that:
ExecuteCommand: CREATE ("MyClass", "1")
Ext.require("MyClass", function(c) {
ExecuteCommand: DOSTUFF (c);
}

Resources