I have a classic asp application which has a following code right when the app opens:
Window.onerror = handleErr
I need add delay in checking error as the error displayed by handleErr function seems to be occurring prematurely. I think it’s caused by network delay. After refreshing app in client browser, the error message goes away. How can add delay before calling ‘window.onerror’?! I want to keep checking for say 5 seconds and call handleErr only if error still persists
I researched settimeout() function and thought I could the line following as:
Window.onerror = settimeout(handleErr,5000)
But it will just delay call but will not recheck that error is still before calling
Thank you, #Ouroborus and #Bergi for your responses.
The fact that if I refresh the page in client browser, the page works fine without onerror exception in other words, the onerror exception occurs prematurely. I simply want to add 5 seconds delay and check for onerror exception again and assign handleErr function only if onerror exception is still true.
Per recommendation of #Ouroborus, I replaced Window.onerror = handleErr with your recommended setTimeout(() => {Window.onerror = handleError}, 5000). It too essentially delayed setting of onerror not sure how to really wait for five seconds and then check again if the window.onerror exception is still true. If it is then only call handleErr function but if not, continue loading the rest of the page. I hope I am making it clear as to what I want to happen. Thanks again and looking forward to further recommendations.
Related
If I access the link in the browser, it returns the expected result most of the times.
Meaning: Sometimes, when I access the url in the browser I get the 400 error (say, 1 in 7 times), but it's fine after a browser refresh.
Also sometimes when it's called with fetch(), it throws the 400 error.
I don't understand why and how to fix it.
I am testing the file in the browser, locally.
Should I write the code to fetch again upon failure? Is that a good practice?
Example code:
fetch('https://my-url/some-code').then(res => res.json()).then(res => res).catch(error => console.log(error));
// randomNum iteration: expected result
// randomNum iteration: expected result
// randomNum iteration: 400 error
Should I write the code to fetch again upon failure? Is that a good practice?
Ideally you wouldn't want to call a second request, because there is most likely an underlying problem on your server that is resulting in this response being a 400 code. I don't see any problems with your current fetch request. If you can't fix your endpoint problem however, then just do the second fetch again. If it is only happening 1/7 times then you're only increasing the average workload time by 12.5%, which isn't a huge deal unless this is a heavily used application.
If a refresh on your browser is needed sometimes however, I'd pursue a bit more troubleshooting to make sure it really is your backend. Does the problem not go away unless you refresh? If so, can you access it correctly by opening a separate instance while the other is in need of a refresh? That would point to front-end possibly.
fetch('https://my-url/some-code').then(res => res.json()).(error => console.log(error);
removing the next then() and remove the error which is not in the ( )
Actually, I want to update a flag in Db using a service call(Delete method) once the user close the browser. I am able to detect browser close action using onbeforeunload and onunload events but async call doesn't work for me(sometimes in debugging mode it works fine but on higher env it doesn't work).
Then, I tried to make sync request but then I found that Chrome now disallows synchronous XHR during page dismissal when the page is being navigated away from or closed by the user.
check link : https://www.chromestatus.com/feature/4664843055398912
I have tried new XMLHttpRequest() as sync, fetch api also Navigator.sendBeacon() but unfortunately nothing works for me.
Please suggest something which works because I have visited so many posts but nothing works for me.
Thanks in advance.
I have some solution for this. Hope so any one of them solves your issue.
constructor() {
window.onbeforeunload = ()=>{
//call API here
}
}
In your component constructor write above code
OR
In my opinion the better idea is making the heartbeat api that sends requests every N seconds to notify server that the session is active and the user is online. On the server check every M minutes if there was no heartbeat requests for more than N seconds: if it is so - execute the API request(what you wanted to execute on crash).
OR
'beforeunload' would be trigger when refreshing pages, closing tab, or closing the browser.
#HostListener('window:beforeunload', ['$event'])
beforeUnload(e: Event) {
e.returnValue = false;
}
OR
It is not possible to ensure that every time an user exits a browser page a specific function will be triggered. The reason is that the browser could close the window for many reasons. Yes it could be a user action but this is not the only case. For example The browser could crash.
In my case I will have to find another strategy to track the time the user stays on the page. For example I am planning to send a lot of API calls before the user exits with all the informations I need to understand his stay on the page. I will update the answer when I will reach a good solution. Anyway I will still wait for better answers.
You can use the fetch API.
The syntax would be:
fetch('API', {
method: 'POST', // Other opn are also supported like GET,PUT DELETE
body: '',
keepalive: true
});
Just an additional read:
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API
When using $http we can set the timeout for it and it will look something like this:
$http.get(url,{timeout: 5000}).success(function(data){});
What is that timeout mean? Is it mean the connection (data download) must be completed within the timeout period? Or it is mean the delay time to receive respond from the server? What would be the best general minimal timeout setting for mobile connection?
If the http request does not complete within the specified timeout time, then an error will be triggered.
So, this is kind of like saying the following to the $http.get() function:
I'd like you to fetch me this URL and get me the data
If you do that successfully, then call my .success() handler and give me the data.
If the request takes longer than 5000ms to finish, then rather than continue to wait, trigger a timeout error.
FYI, it looks to me like AngularJS has converted to using standard promise syntax, so you should probably be doing this:
$http.get(url,{timeout: 5000}).then(function(data){
// successfully received the data here
}, function(err) {
// some sort of error here (could be a timeout error)
});
What is that timeout mean? Is it mean the connection (data download) must be completed within the timeout period?
Yes. If not completed within that time period, it will return an error instead. This avoids waiting a long time for a request.
Or it is mean the delay time to receive respond from the server?
No, it is not a delay time.
What would be the best general minimal timeout setting for mobile connection?
This is hard to say without more specifics. Lots of different things might drive what you would set this to. Sometimes, there is no harm in letting the timeout be a fairly long value (say 120 seconds) in case the server or some mobile link happens to be particularly slow some day and you want to give it as much chance as possible to succeed in those circumstances. In other cases (depending upon the particular user interaction), the user is going to give up anyway if the response time is more than 5 seconds so there may be no value in waiting longer than that for a result the user will have already abandoned.
timeout – {number|Promise} – timeout in milliseconds, or promise that should abort the request when resolved.
Source
Timeout means "perform an action after X time", in JS anyway.
I'm writing a mobile app for Android using Phonegap (cli v5.3.6) and I'm using phonegap-plugin-push v1.3 for registering the device with GCM and handling the notifications as they arrive at the device.
// define the push settings
var push = PushNotification.init({
"android": {
"senderID": "*********"
},
"ios": {},
"windows": {}
});
push.on("notification", function(data) {
console.log("notification received while in app");
console.log(JSON.stringify(data));
addMessageToLocalDB(data, false);
});
push.on("error", function(e) {
console.log(JSON.stringify(e));
});
It works well when the app is either closed or in the background. My problem occurs when the app is in the foreground. I'm looking at the logcat and see that the notification is received, but I'm not seeing my logging to show that the callback function is fired (and obviously, the outcome I'm expecting to see isn't happening). I'm also not seeing the callback function of the error event firing, so it probably isn't really failing.
Am I missing something? I couldn't find anything online about this problem and I can't really read java to understand how the plugin is supposed to behave...
Edit: I just figured out something. The logs that indicate on the arrival of the push notification occur even if I remove the code from my javascript - the PushNotification init and on("notificataion") functions.
I'm therefore finding myself a bit confused as to where I need to place the init and event handler functions.
My app consists of index.html (which is the page that loads when the app starts) and many other html files (which each act as a separate page of the app. Shouldn't I put the event handler on each individual page? That what I did try...
Thanks,
Yosi.
You might need to wait for the deviceready event, before calling PushNotification.init. This might be more reliable (and quicker) than using setTimeout.
I might not get your questuion but if you want to show notification when the app is in foreground .The default value for forceshow parameter is false and you are right it's n't failing
"android": {
"senderID": "*********",
"forceShow" : "true"
},
I eventually noticed that the PushNotification object is sometimes undefined when I first load the page, but then if I wait enough time (100ms), it is then defined.
What I ended up doing is an interval to run every 100ms, check if the PushNotification object is defined and if so, run my init+event listener code and clear the interval. This seems to be working well for quite some time.
I'm playing around with implementing a JavaScript server ping tool based on the accepted answer given on this question: Is it possible to ping a server from Javascript?. This essentially works by assuming the pinged server is down if no response has been given after n milliseconds.
That's great, and it's a pretty cool way of doing it, however there are two rather large pitfalls:
Not all servers do respond within the allocated time.
Sometimes an ERR_CONNECTION_TIMED_OUT error is thrown before our timeout timer has finished.
Both of these things cause incorrect results. The former suggests that the server is offline when it's possibly online and responding slowly, and the latter suggests the server is online when it's (likely) offline.
In an ideal world this code would capture what type of error thrown was thrown and handle this appropriately. After all, if the error thrown is a 404 Not Found error, this counter-intuitively means the server is online and has responded.
If we log the image error event, the only thing we see surrounding the error is:
Event {
...
type: "error"
}
There's no message or anything hinting at what the error thrown was, and both the 404 and ERR_CONNECTION_TIMED_OUT errors give identical information.
What can I do to capture the ERR_CONNECTION_TIMED_OUT error I see in Chrome's JavaScript console, rather than relying on a fixed-speed timer?
Update
The best way I can replicate this issue is by altering Trante's JSFiddle demo (as linked to in the question I've linked above) to use a 30000ms timer rather than a 1500ms timer:
this.timer = setTimeout(function () {
if (_that.inUse) {
_that.inUse = false;
_that.callback('timeout');
}
}, 30000);
The 'unknown' server should obviously not respond, but instead we see this:
In Chrome's console, the following error has been thrown:
Failed to load resource: net::ERR_NAME_NOT_RESOLVED
As the Image's onerror function has been fired with the generic error as given above, the function believes this to mean that 1. 'unknown' exists, and 2. it's online. The ERR_NAME_NOT_RESOLVED error appears to be something which only Chrome is aware of, and isn't passed through to the error event at all.
Update 2
Today I tried doing this with web sockets instead of images and unfortunately these suffer from the same problem. The only data surrounding the error returned is type: "error" - no information about what the error actually was.