I've tried to implement long polling chat. My chat works correctly, except one browser - safari.
I get new message by this code (here only part, just for understanding recursion):
let errorCounter = 0;
let getChatText = function () {
let options = {
//headers and other configuration, which needed for XMLHttpRequest
};
let responseHandler = function(responseCode, body) {
switch (responseCode) {
//handle response codes
case 200:
errorCounter = 0; //on success response
// other codes handle here
default:
errorCounter++;
}
if (errorCounter >= 30) { // 30 just for testing
endChatSession(true);
} else {
getChatText(); //recursion
}
};
requestCall(options, false, responseHandler);
};
If in some moment I reload the page - it doesn't stop, but tryis to call many times (30 in my case) and endChatSession on too many errors. But in other browsers (chrome, firefox etc.) - its immediately stops recursion, and reload the page.
Here is a console output, before safari page reload (preserve log):
Question: How can I stop recursion on page reload in safari, because it is not a reason to endChatSession
Related
I'm using osx 10.9.2, protractor 0.21.0, selenium-server-standalone 2.40.0 and chromedriver 2.9.
I'm having some problems, which (I believe) was due to window focusing issue.
When I run my e2e test using protractor, the browser window would show but my terminal will still be the one in focus. This is apparent from "Terminal" was still shown in my menu bar rather than "Chrome" (osx behavior that indicates which app is in focus).
I tried to remedy the situation by doing this to no avail:
browser.driver.getAllWindowHandles().then(function(handles) {
console.log(handles[0]);
browser.driver.switchTo().window(handles[0]);
});
This situation causes some of my tests to fail. For example, tests that include clicking a field with bootstrap datepicker won't show the calendar and making my test cannot interact with the datepicker calendar.
The situation is even worse on firefox. Firefox won't even show any dropdown menu when clicked if the browser is not in focus.
Funnily, when I click the browser window manually after it shows up the first time, the tests will work normally.
When I tried a different approach: Doing the test on a freshly installed debian linux, still not working. Behavior is similar as described above.
These are my configuration files: https://gist.github.com/giosakti/ca24a13705d15f4374b0
Unfortunately IE & Firefox don't ensure the windows handlers order, so we need iterate them. And getting focus on the new browser window/tab can be tricky too.
I've run into these issues so i created:
A helper function to overcome those issues
// Needs an element to make sure we are on the correct popup
var waitForPopUpHandle = function(elm, errorMessage) {
if (errorMessage == null) {
errorMessage = 'Expected a new browser tab or window to pop up';
};
if (elm == null) {
throw 'waitForPopUpHandle needs an element to wait for!';
};
browser.ignoreSynchronization = true; // not a protractor page
// IE & Firefox don't ensure the windows handlers order, so we need iterate them.
// First wait to have more that 1 browser tab
browser.manage().timeouts().implicitlyWait(300); // a reasonable wait-retry time
var i = 0;
var popUpHandle = browser.driver.wait(function() {
return browser.getAllWindowHandles().then(function(handles) {
if (handles.length > 1) {
return browser.switchTo().window(handles[i]).then(function() {
return browser.driver.isElementPresent(elm).then(function(result) {
if (result) {
return handles[i];
} else {
browser.sleep(400); // give it a break
i = i + 1;
if (i >= handles.length) {
i = 0;
};
return false;
};
});
});
} else {
browser.sleep(400); // give it a break
return false;
};
});
}, browser.params.timeouts.pageLoadTimeout, errorMessage);
// restore implicit wait
browser.manage().timeouts().implicitlyWait(0); //restore
return popUpHandle;
};
Sample usage of that helper
var popUpHandle = waitForPopUpHandle(by.css('div.some-element-unique-to-that-popup'));
browser.switchTo().window(popUpHandle).then(function() {
browser.ignoreSynchronization = true; // not an angular page
browser.driver.findElement(by.css('div.some-element-unique-to-that-popup')); // wait for the elm
// your expect()'s go here ...
// ...
browser.close().then(function() {
// This close() promise is necessary on IE and probably on Firefox too
var mainTab = waitForMainWindow();
expect(browser.switchTo().window(mainTab).then(function() {
browser.ignoreSynchronization = false; // restore if main window is an angular page
// Ensure we are back on the main window
// ....
return true;
})).toBe(true);
});
});
And finally waitForMainWindow helper
var waitForMainWindow = function(errorMessage) {
if (errorMessage == null) {
errorMessage = 'Expected main browser window to be available';
};
browser.ignoreSynchronization = true; // not an angular page
return browser.driver.wait(function() {
return browser.getAllWindowHandles().then(function(handles) {
if (handles.length > 1) {
var hnd = handles[handles.length - 1];
return browser.switchTo().window(hnd).then(function() {
return browser.close().then(function() {
browser.sleep(400); // wait for close
return false;
});
});
} else {
return handles[0];
};
});
}, 5000, errorMessage);
};
I found a silver lining! I downgrade the chrome using installer from http://google-chrome.en.uptodown.com/mac/old and the focus issues are gone.. (the issues still persist on firefox though)..
If you search "chrome 34 focus issues" on google, you will find several reports that maybe correlate with this issue. for example: https://productforums.google.com/forum/#!topic/chrome/pN5pYf2kolc
but I still don't know whether this was a bug or expected behavior of chrome 34. So for now I block google updater and use Chrome 33.
Is it possible to detect situation when page is entered and when the same page is refreshed
if (entered) alert("hi");
if (refreshed) alert("you've refreshed");
Somehow there are some little differences between page rendering when entered and when refreshed and it would be much easier to detect the case than to debug it for me (if its even possible - maybe some browser optimization stuff is causing it).
This isn't an ideal solution, but if your page can load in under 5 seconds than this will work, and assuming you are not navigation to another page, then returning within 5 seconds.
window.onbeforeunload = function(){
window.sessionStorage.setItem('lastvisit', new Date().getTime());
}
var lastVisit = +window.sessionStorage.getItem('lastvisit');
var isRefresh = (new Date().getTime() - lastVisit) < 5000;
console.log(isRefresh);
There is no perfect way of tracking reloads verses new page loads but this solution works in most situations. Use sessionStorage in combination with an unload event:
(function (win) {
'use strict';
var reloaded = false,
ss = win.sessionStorage,
offset = 1000, // 1 second, may need tweaking if
// your page takes a long time to load/where
// this code is located in your page
now = function () {
return (new Date()).getTime();
},
lastUnload = ss.getItem('lastunload'),
loadStatus = document.getElementById('status');
// sessionStorage returns null if nothing was stored
if (lastUnload !== null) {
// sessionStorage returns a string, +lastUnload
// coerces the string held in lastUnload into an integer
// see https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/Arithmetic_Operators#-_.28Unary_Negation.29
if (+lastUnload + offset > now()) {
reloaded = true;
}
}
win.addEventListener('unload', function () {
ss.setItem('lastunload', now());
}, false);
if (lastUnload === null) {
loadStatus.innerHTML = 'First visit of session.';
} else if (reloaded) {
loadStatus.innerHTML = 'Page was reloaded.';
} else {
loadStatus.innerHTML = 'Navigated back to page after leaving';
}
}(window));
This code defines a page reload as returning to the page within 1 second of leaving it, so there could be false positives if someone leaves the page and immediately hits the back button but with normal browsing behavior that really shouldn't happen. You can modify the offset variable if you want to give more or less leeway, but 1 second seems to be a good default.
After developing this code I also found this similar answer.
If sessionStorage is available, you can use that.
if (!window.sessionStorage.getItem('visited')) {
//entered
window.sessionStorage.setItem('visited', true);
}
else {
//refreshed
}
More on sessionStorage
Here is my AJAX function:
/**
* Send an AJAX request
*
* #param url The URL to call (located in the /ajax/ directory)
* #param data The data to send (will be serialised with JSON)
* #param callback The function to call with the response text
* #param silent If true, doesn't show errors to the user
* #param loader The element containing "Loading... Please wait"
*/
AJAX = function(url,data,callback,silent,loader) {
var a,
attempt = 0,
rsc = function() {
if( a.readyState == 4) {
if( a.status != 200) {
if( a.status > 999) { // IE sometimes throws 12152
attempt++;
if( attempt < 5)
send();
else if( !silent) {
alert("HTTP Error "+a.status+" "+a.statusText+"<br />Failed to access "+url);
}
}
else if(!silent) {
alert("HTTP Error "+a.status+" "+a.statusText+"\nFailed to access "+url);
}
}
else {
callback(JSON.parse(a.responseText));
}
}
},
to = function() {
a.abort();
attempt++;
if( attempt < 5)
send();
else if( !silent) {
alert("Request Timeout\nFailed to access "+url);
}
};
data = JSON.stringify(data);
var send = function() {
if( loader && attempt != 0) {
loader.children[0].firstChild.nodeValue = "Error... retrying...";
loader.children[1].firstChild.nodeValue = "Attempt "+(attempt+1)+" of 5";
}
a = new XMLHttpRequest();
a.open("POST","/ajax/"+url,true);
a.onreadystatechange = rsc;
a.timeout = 5000;
a.ontimeout = to;
a.setRequestHeader("Content-Type","application/json");
a.send(data);
};
send();
};
The general idea is to attempt the request up to five times. Sometimes IE fails with an unusual HTTP error (12xxx), and sometimes the server may fail to respond.
The problem I'm having is that the abort() call doesn't appear to be aborting the connection. To test, I made a simple PHP script:
<?php
sleep(60);
touch("test/".uniqid());
die("Request completed.");
?>
The touch() call creates a file with the current uniqid() - by looking at the modification time I can see the time the sleep(60) ended.
Expected behaviour:
The request is sent
After five seconds, the text changes to "Error... Retying... Attempt 2/5"
Repeat the above up until Attempt 5/5, then fail.
The five calls to the PHP file are aborted, and either there will be five files in the "test" folder, spaced 5 seconds apart, or there will be none because ignore_user_abort is off.
Observed behaviour (in IE9):
The request is sent
The attempt text appears and changes as it should
After five attempts, the error message is displayed
I am unable to load any pages for five whole minutes.
On the server, there are five files spaced one minute apart
I don't know what to make of this, because on the server side Requests 3, 4 and 5 are being sent minutes after the "Timeout" error message is shown on the browser.
If it makes any difference, the page making the AJAX calls is in an iframe. Reloading the iframe (using iframe.contentWindow.location.reload() does NOT fix the issue, it still waits for those five requests to go through.
Why is this happening? How can I fix it?
EDIT: I've run the test again using Developer Tools to monitor network activity. The result is:
URL Method Result Type Received Taken Initiator
/ajax/testto (Aborted) 0 B < 1 ms (Pending...)
/ajax/testto (Aborted) 0 B 125 ms (Pending...)
/ajax/testto (Aborted) 0 B 125 ms (Pending...)
/ajax/testto (Aborted) 0 B 125 ms (Pending...)
/ajax/testto (Aborted) 0 B 124 ms (Pending...)
The problem seems to be that timeout and ontimeout aren't yet part of some implementations:
var hasTimeout = 'timeout' in new XMLHttpRequest(); // false
At least, it's not in Chrome 16 or Firefox 7. And, this should return true given the requirements:
The timeout attribute must return its value. Initially its value must be zero.
Both have been part of the XHR 2 spec since Sept 7, 2010. But, as the "Level 2" spec has been been around since Feb 25, 2008 and is still a "Working Draft," there's not really a guarantee that any implementation would be up-to-date with the spec.
Without those available to you, you can try instead using onabort and setTimeout (as you stated in your comment):
// snip
to = function() {
attempt++;
if( attempt < 5)
send();
else if( !silent) {
console.log("Request Timeout\nFailed to access "+url);
}
};
// snip
var send = function() {
if( loader && attempt != 0) {
loader.children[0].firstChild.nodeValue = "Error... retrying...";
loader.children[1].firstChild.nodeValue = "Attempt "+(attempt+1)+" of 5";
}
a = new XMLHttpRequest();
a.open("POST","/ajax/"+url,true);
a.onreadystatechange = rsc;
setTimeout(function () { /* vs. a.timeout */
if (a.readyState < 4) {
a.abort();
}
}, 5000);
a.onabort = to; /* vs. a.ontimeout */
a.setRequestHeader("Content-Type","application/json");
a.send(data);
console.log('HTTP Requesting: %s', url);
};
// snip
Example: http://jsfiddle.net/AmQGM/2/ -- The ?delay=2 should finish, while the ?delay=10 expires its 5 tries.
When running your code, I got the error c00c023f. When I googled it, it came up with this answer:
http://www.enkeladress.com/article.php/internetexplorer9jscripterror
This sounds very similar to what you're experiencing.
Here's a SO question which has the same problems, with a solution (also based on the above link, but with additional information): IE 9 Javascript error c00c023f
Before aborting the request, try setting
a.onreadystatechange = function() {};
after that, also add a check around calling abort:
if( a.readyState > 0 && a.readyState < 4 ) {
a.abort();
}
I had the same problem, it turned out to be the issue with PHP session.
If the session is open, all other requests from the same session must wait.
<?php
session_write_close();
sleep(60);
touch("test/".uniqid());
die("Request completed.");
?>
This, of course, would not help you if you haven't started the session :)
Boy-oh-boy do I hate external interface. I have a video player that utilizes external interface to control the flash object and to allow the flash object to pass messages to the same javascript. For a time it worked well in all browsers. Then a few days ago i went to go test it in all browsers before i moved the project out of development, and found that the application broke in internet explorer 9. The following error appeared in the console:
SCRIPT16389: Could not complete the operation due to error 8070000c.
jquery.min.js, line 16 character 29366
My javascript file is really long but here are the important parts. All my actions are contained in an object that i created. Inside one of my methods i have the following lines:
var that = this;
that.stop();
here are all the methods that get called as a result of that method:
this.stop = function(){
var that = this;
console.log('stop called');
that.pause();
that.seek(0);
that.isPlaying = false;
console.log('stop finished');
};
this.pause = function(){
var that = this;
console.log('pause called');
if(that.player == 'undefined' || that.player == null){
that.player = that.GetMediaObject(that.playerID);
}
that.player.pauseMedia(); //external interface call
that.isPlaying = false;
console.log('pause finished');
};
this.seek = function(seek){
var that = this;
console.log('seek called');
if(that.player == 'undefined' || that.player ==null){
console.log("player="+that.player+". resetting player object");
that.player = that.GetMediaObject(that.playerID);
console.log("player="+that.player);
}
that.player.scrubMedia(seek); //external interface call
console.log('seek finished');
};
//this method returns a reference to my player. This method is call once when the page loads and then again as necessary by all methods that make external interface calls
this.GetMediaObject = function(playerID){
var mediaObj = swfobject.getObjectById(playerID);
console.log('fetching media object: ' +mediaObj );
//if swfobject.getObjectById fails
if(typeof mediaObj == 'undefined' || mediaObj == null){
console.log('secondary fetch required');
var isIE = navigator.userAgent.match(/MSIE/i);
mediaObj = isIE ? window[playerID] : document[playerID];
}
return mediaObj;
};
Here's the output from my console.log statments:
LOG: fetching media object: [object HTMLObjectElement]
LOG: video-obj-1: ready
LOG: stop called
LOG: pause called
LOG: pause finished
LOG: seek called
LOG: player=[object HTMLObjectElement]
SCRIPT16389: Could not complete the operation due to error 8070000c.
jquery.min.js, line 16 character 29366
The interesting thing is that it appears that the first external interface call 'that.player.pauseMedia()' doesn't have any issue, but the subsequent call to 'that.player.scrubMedia(0)' fails. Another odd thing is that it points to jquery as the source of the error, but there's no call to jquery in those functions.
Here's what i know it's not. It is not an issue where my timing is off. The last line of my actionscript sends a message to the javascript when the flash object has completely loaded. Also i set the parameter 'allowScriptAccess' to 'always' so it's not that either. The actionscript file we use has been used in previous projects so i am 90% certain that that is not the issue.
here's my actionscript anyways. I didn't write actionscript and i'm not too familiar with the language but I tried to put in the parts that seemed most pertinent to my application:
flash.system.Security.allowDomain("*.mydomain.com");
import flash.external.ExternalInterface;
// variables to store local information about the current media
var mediaEmbedServer:String = "www";
var mediaPlayerID:String;
var mediaFile:String;
var mediaDuration:Number;
// variables to be watched by actionscript and message javascript on changes
var mediaPositions:String = "0,0"; // buffer position, scrub position
var mediaStatus:String;
var netStreamClient:Object = new Object();
netStreamClient.onMetaData = metaDataHandler;
netStreamClient.onCuePoint = cuePointHandler;
var connection:NetConnection;
var stream:NetStream;
var media:Video = new Video();
// grab the media's duration when it becomes available
function metaDataHandler(info:Object):void {
mediaDuration = info.duration;
}
function cuePointHandler(info:Object):void {
}
connection = new NetConnection();
connection.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler);
connection.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
try {
var paramName:String;
var paramValue:String;
var paramObject:Object = LoaderInfo(this.root.loaderInfo).parameters;
for (paramName in paramObject) {
paramValue = String(paramObject[paramName]);
switch (paramName){
case "server":
mediaEmbedServer = paramValue;
break
case "playerID":
mediaPlayerID = paramValue;
break
}
}
} catch (error:Error) {
}
if (mediaEmbedServer == "dev" || mediaEmbedServer == "dev2"){
connection.connect("rtmp://media.developmentMediaServer.com/myApp");
} else {
connection.connect("rtmp://media.myMediaServer.com/myApp");
}
function securityErrorHandler(event:SecurityErrorEvent):void {
trace("securityErrorHandler: " + event);
}
function connectStream():void {
stream = new NetStream(connection);
stream.soundTransform = new SoundTransform(1);
stream.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler);
stream.client = netStreamClient;
media.attachNetStream(stream);
media.width = 720;
media.height = 405;
addChild(media);
}
function netStatusHandler(stats:NetStatusEvent){
switch (stats.info.code){
case "NetConnection.Connect.Success":
connectStream();
break;
case "NetConnection.Call.BadVersion":
case "NetConnection.Call.Failed":
case "NetConnection.Call.Prohibited":
case "NetConnection.Connect.AppShutdown":
case "NetConnection.Connect.Failed":
case "NetConnection.Connect.InvalidApp":
case "NetConnection.Connect.Rejected":
case "NetGroup.Connect.Failed":
case "NetGroup.Connect.Rejected":
case "NetStream.Connect.Failed":
case "NetStream.Connect.Rejected":
case "NetStream.Failed":
case "NetStream.Play.Failed":
case "NetStream.Play.FileStructureInvalid":
case "NetStream.Play.NoSupportedTrackFound":
case "NetStream.Play.StreamNotFound":
case "NetStream.Seek.Failed":
case "NetStream.Seek.InvalidTime":
// report error status and reset javascriptPlay
clearInterval(progressInterval);
messageStatus("error");
break;
default:
// check time through file to determine if media is over
if (stream.time > 0 && stream.time >= (mediaDuration - .25)){
// reset media if it has ended
clearInterval(progressInterval);
stream.play(mediaFile, 0, 0);
messageStatus("finished");
}
}
};
var progressInterval:Number;
// respond to a play/pause request by playing/pausing the current stream
function pauseMedia(){
clearInterval(progressInterval);
if (mediaStatus == 'playing'){
stream.pause();
messageStatus("paused");
}
};
ExternalInterface.addCallback( "pauseMedia", pauseMedia );
// respond to a scrub request by seeking to a position in the media
function scrubMedia(newPosition){
clearInterval(progressInterval);
if (mediaStatus == "playing"){
stream.pause();
messageStatus("paused");
}
stream.seek(newPosition * mediaDuration);
var positionSeconds = newPosition * mediaDuration;
messagePositions(positionSeconds+","+positionSeconds);
};
ExternalInterface.addCallback( "scrubMedia", scrubMedia );
ExternalInterface.call("MediaPlayerReady", mediaPlayerID);
Sounds like an undefined expando property which may be caused by a jQuery IE9 bug. The best way to debug it is to remove the userAgent test and replace it with a check for the object element, such as:
document.getElementsByTagName("object")[0].outerHTML
to see whether the ID attribute is being changed after the first click by jQuery.
I had this problem using JPEGCam, which also uses flash's external interface. My webcam control was being loaded dynamically within a div, and would then throw this error in IE (not firefox or chrome). After moving the initialization of my flash control to document.ready in the parent page, then hiding/showing/moving the control as needed, i was able to work around this exception.
Hope that helps.
I've built a simple JavaScript-based timer for a mobile webapp; for the sake of example:
var a = 0;
setInterval(function() {
console.log('a', a);
a++;
}, 1000);
This runs just fine in both Mobile Safari and Android Browser. It will log to console every second and increment the value of a accordingly. (Okay, Android Browser doesn't have console.log support, but let's assume it does.)
The issue: if the screen times out (i.e. user stopped interacting with the page), the setInterval function pauses. It resumes when the user turns on their screen again. This won't work for me as I need timer to keep running.
The questions: Is there a way to prevent the setInterval function from pausing when the screen times out? If not, is it possible to prevent the screen from timing out? Any other alternatives?
Thanks in advance!
Basically, no. The phone enters a sleep state to save battery when the screen times out. Since you can't see anything anyway, a large number of processing tasks are stopped. Similar things will occur when you change tabs/windows (the page is unloaded from memory). Right now there is no way to request that the device stays on from a web application. Future support in Android for accessing hardware may provide this functionality, but personally I doubt it.
If you need always running support, you'll need to write native applications for both systems (plus on Android it can always run).
You can use the Page Visibility API to detect when the page is hidden or visible. For example, if the user navigates away from the browser and back again or the screen turns off and on.
I used this answer to help create by solution.
You will need to store the time you set your interval. Then when the visibilityChange event listener indicates the document is visible again, you can calculate the amount of time that has passed since you first started the interval and update your data as needed.
In my case I was creating a count down timer in my Angular2 project. My page was running on an iPad and the timer was pausing whenever the screen turned off. So I added the event listener in my ngOnInit(). Then when the screen turned back on I could update my timer to show the correct time left since it was started.
I am using the moment npm package to handle my date time.
The timerInfo object is a class variable that gets updated by the interval callback. self.zone.run() is used to propagate the changes to the DOM so that the updated time gets displayed.
Written in typescript:
private timerInfo:{
days?:number,
hours?:number,
minutes:number,
seconds:number
};
private startTime:Moment = moment();
private timerDuration:number = 20; // in minutes
private timerHandle:any;
ngOnInit() {
this.setVisibilityListener();
}
private setVisibilityListener():void {
var self = this;
var hidden, visibilityState, visibilityChange;
if (typeof document.hidden !== "undefined") {
hidden = "hidden";
visibilityChange = "visibilitychange";
visibilityState = "visibilityState";
}
var document_hidden = document[hidden];
document.addEventListener(visibilityChange, function () {
if (document_hidden != document[hidden]) {
if (document[hidden]) {
// Document hidden
console.log("document hidden");
} else {
// Document shown
console.log("document shown; setCountDownTimer()");
self.setCountDownTimer();
}
document_hidden = document[hidden];
}
});
}
private setCountDownTimer():void {
var self = this;
if (self.startTime) {
var startMoment = moment(self.startTime);
var endMoment = startMoment.add(self.timerDuration, "minutes");
console.log("endMoment: ", endMoment.toISOString());
self.clearTimer();
var eventTime = endMoment.unix();
var currentTime = moment().unix();
var diffTime = eventTime - currentTime;
var duration = moment.duration(diffTime * 1000, 'milliseconds');
var interval = 1000;
// if time to countdown
if (diffTime > 0) {
self.timerHandle = setInterval(() => {
self.zone.run(() => {
var diff = duration.asMilliseconds() - interval;
if (diff < 0) {
self.clearTimer();
self.timerComplete();
} else {
duration = moment.duration(duration.asMilliseconds() - interval, 'milliseconds');
self.timerInfo = {
days: moment.duration(duration).days(),
hours: moment.duration(duration).hours(),
minutes: moment.duration(duration).minutes(),
seconds: moment.duration(duration).seconds()
};
// console.log("timerInfo: ", JSON.stringify(self.timerInfo));
}
});
}, 1000);
} else {
self.timerComplete();
}
}
}
private clearTimer():void {
if (this.timerHandle) {
clearInterval(this.timerHandle);
this.timerHandle = null;
}
}