I need to implement a javascript where I can detect if my deep link is worked or not, If it works then it should remain same but if it does not work then it must start download file.
For that, i use timeout function to do it. Here is sample code I used.
setTimeout(function () { window.location = "https://itunes.apple.com/appdir"; }, 25);
window.location = "appname://";
But this code works fine on android and ios but it is creating problem while it comes to the desktop browser. In desktop browser after Deeplink works properly, timeout function do not stops and it redirects to download page.
so finally I want some event which can detect if my Deeplink is worked or not so I can set cleartimeout function to prevent redirecting to downloading URL
I have been facing similar problem, and finally I have found a nice botched job to make it work:
var timer = null;
function setListener() {
window.document.addEventListener("visibilitychange", function(e) {
window.clearTimeout(timer);
timer = null;
window.open('','_self').close();
});
}
function redirectAndroid() {
setTimeout(function () { window.location = "https://itunes.apple.com/appdir"; }, 25);
window.location = "appname://";
}
function redirecIOS() {
setListener();
var beforeApp = new Date().valueOf();
window.location.href = "appname://";
var afterApp = new Date().valueOf();
if (afterApp - beforeApp < 100) {
setTimeout(function() {
"https://itunes.apple.com/appdir";
}, 25);
} else {
if (timer === null) {
timer = setTimeout(function() {
"https://itunes.apple.com/appdir";
}, 200);
}
}
This way, after redirecting to application, if it opens it triggers the event "visibilitychange" before the timeout function, and you clear the timeout avoiding it to redirect to web, and close the browser (if you want). If application is not installed, timeAfterApp - timeBeforeApp is not < 100 so there you set the timeout.
For desktop browser, consider using window blur listener and act accordingly
Blur listener will tell you if user left the tab or browser
window.onblur=()=>{//deeplink check (maybe unsuccessfull?)
window.onfocus=()=>{//deeplink unsucesfull};
}
I would try with a timestamp expression in the timeout.
Something like this (play around with the thresholds as needed):
var clickedTm = +new date;
setTimeout(function () {
if (+new date - clickedTm < 600) {
window.location = "https://itunes.apple.com/appdir";
}
}, 500);
window.location = "appname://";
Related
We need a solution to the following issue.
We currently refresh a screen every 30 seconds, what we need to do prior to the actual refresh is check if the website is still up and if there is a network present to access the page.
If the page is down then we delay the refresh by 6 seconds this is repeated 5 times.
If the fifth attempt is showing that the website is still down then an error message is displayed.
This is working fine but we need to check if the website is still available (ping the website prior to refreshing) and also we need a solution if the browser starts to refresh but loses the connection or the server goes down once the refresh has started
This is the current code
window.onload = function () {
var refresh_rate = 30; //<-- Second until refresh
var connection_attempts=5; ////// Connection attempts
var failed_seconds=6;
var inactivity_counter = 0;
var connection_failed= 0;
function reset1() {
inactivity_counter = 0;
console.log("Reset1");
}
function reset2() {
inactivity_counter = 0;
console.log("Reset2");
}
function reset3() {
inactivity_counter = 0;
connection_failed = 0;
console.log("Reset3");
}
function reset_network() {
inactivity_counter = (refresh_rate - failed_seconds);
console.log("ResetNetwork");
}
setInterval(function () {
inactivity_counter++;
refreshCheck();
}, 1000);
function can_i_refresh() {
if (inactivity_counter >= refresh_rate) {
return true;
}
return false;
}
function refreshCheck() {
if (can_i_refresh()) {
if(navigator.onLine) {
connection_failed='0';
window.location.href='alreadybooked.php?location=5';
inactivity_counter = 0;
}
else {
connection_failed++;
console.log(connection_failed);
if(connection_failed==connection_attempts) {
alert("Error 1001: This check-in device is currently experiencing issues. Please check-in on another device. If you still experience issues, please press the 'OK' button and proceed to reception");
return false;
}
reset_network();
}
}
else {
console.log(inactivity_counter);
}
}
window.addEventListener("click", reset1);
window.addEventListener("mousemove", reset2);
};
This should do what you need.
The function setupPageReload() creates a timeout so that the page reload will start after the specified delay. The actual reload is done into a temporary element, so the check for availability and the reload are the same thing. If the reload doesn't happen (for any reason) then the fail counter is incremented and will execute the fatalError() function if there have been enough retries. If it works then it simply replaces the contents of the current page with the contents that were just downloaded. Unless there was a "fatal error" then the function is simply executed again to start the process all over.
var refreshRate = 30;
var connectionAttempts = 5;
var connectionFailed = 0;
function setupPageReload() {
setTimeout(function() {
$("<div/>").load(location.href + " body", function(response, status) {
if (status == "success") {
connectionFailed = 0;
$("body").html(response);
setupPageReload();
}
else {
if (++connectionFailed === connectionAttempts) {
fatalError();
}
else {
setupPageReload();
}
}
});
}, refreshRate * 1000);
}
function fatalError() {
alert("Error 1001: This check-in device is currently experiencing issues. " +
"Please check-in on another device. If you still experience issues, " +
"please press the 'OK' button and proceed to reception");
}
window.onload = setupPageReload;
Incidentally, this method requires jQuery as that performs the ajax download and gets the content of the <body/> tag much, much easier than if you were to do that in vanilla js. If you don't already use that in the page in question then you'll need to add a script include.
Rewriting the question -
I am trying to make a page on which if user leave the page (either to other link/website or closing window/tab) I want to show the onbeforeunload handeler saying we have a great offer for you? and if user choose to leave the page it should do the normal propogation but if he choose to stay on the page I need him to redirect it to offer page redirection is important, no compromise. For testing lets redirect to google.com
I made a program as follows -
var stayonthis = true;
var a;
function load() {
window.onbeforeunload = function(e) {
if(stayonthis){
a = setTimeout('window.location.href="http://google.com";',100);
stayonthis = false;
return "Do you really want to leave now?";
}
else {
clearTimeout(a);
}
};
window.onunload = function(e) {
clearTimeout(a);
};
}
window.onload = load;
but the problem is that if he click on the link to yahoo.com and choose to leave the page he is not going to yahoo but to google instead :(
Help Me !! Thanks in Advance
here is the fiddle code
here how you can test because onbeforeunload does not work on iframe well
This solution works in all cases, using back browser button, setting new url in address bar or use links.
What i have found is that triggering onbeforeunload handler doesn't show the dialog attached to onbeforeunload handler.
In this case (when triggering is needed), use a confirm box to show the user message. This workaround is tested in chrome/firefox and IE (7 to 10)
http://jsfiddle.net/W3vUB/4/show
http://jsfiddle.net/W3vUB/4/
EDIT: set DEMO on codepen, apparently jsFiddle doesn't like this snippet(?!)
BTW, using bing.com due to google not allowing no more content being displayed inside iframe.
http://codepen.io/anon/pen/dYKKbZ
var a, b = false,
c = "http://bing.com";
function triggerEvent(el, type) {
if ((el[type] || false) && typeof el[type] == 'function') {
el[type](el);
}
}
$(function () {
$('a:not([href^=#])').on('click', function (e) {
e.preventDefault();
if (confirm("Do you really want to leave now?")) c = this.href;
triggerEvent(window, 'onbeforeunload');
});
});
window.onbeforeunload = function (e) {
if (b) return;
a = setTimeout(function () {
b = true;
window.location.href = c;
c = "http://bing.com";
console.log(c);
}, 500);
return "Do you really want to leave now?";
}
window.onunload = function () {
clearTimeout(a);
}
It's better to Check it local.
Check out the comments and try this: LIVE DEMO
var linkClick=false;
document.onclick = function(e)
{
linkClick = true;
var elemntTagName = e.target.tagName;
if(elemntTagName=='A')
{
e.target.getAttribute("href");
if(!confirm('Are your sure you want to leave?'))
{
window.location.href = "http://google.com";
console.log("http://google.com");
}
else
{
window.location.href = e.target.getAttribute("href");
console.log(e.target.getAttribute("href"));
}
return false;
}
}
function OnBeforeUnLoad ()
{
return "Are you sure?";
linkClick=false;
window.location.href = "http://google.com";
console.log("http://google.com");
}
And change your html code to this:
<body onbeforeunload="if(linkClick == false) {return OnBeforeUnLoad()}">
try it
</body>
After playing a while with this problem I did the following. It seems to work but it's not very reliable. The biggest issue is that the timed out function needs to bridge a large enough timespan for the browser to make a connection to the url in the link's href attribute.
jsfiddle to demonstrate. I used bing.com instead of google.com because of X-Frame-Options: SAMEORIGIN
var F = function(){}; // empty function
var offerUrl = 'http://bing.com';
var url;
var handler = function(e) {
timeout = setTimeout(function () {
console.log('location.assign');
location.assign(offerUrl);
/*
* This value makes or breaks it.
* You need enough time so the browser can make the connection to
* the clicked links href else it will still redirect to the offer url.
*/
}, 1400);
// important!
window.onbeforeunload = F;
console.info('handler');
return 'Do you wan\'t to leave now?';
};
window.onbeforeunload = handler;
Try the following, (adds a global function that checks the state all the time though).
var redirected=false;
$(window).bind('beforeunload', function(e){
if(redirected)
return;
var orgLoc=window.location.href;
$(window).bind('focus.unloadev',function(e){
if(redirected==true)
return;
$(window).unbind('focus.unloadev');
window.setTimeout(function(){
if(window.location.href!=orgLoc)
return;
console.log('redirect...');
window.location.replace('http://google.com');
},6000);
redirected=true;
});
console.log('before2');
return "okdoky2";
});
$(window).unload(function(e){console.log('unloading...');redirected=true;});
<script>
function endSession() {
// Browser or Broswer tab is closed
// Write code here
alert('Browser or Broswer tab closed');
}
</script>
<body onpagehide="endSession();">
I think you're confused about the progress of events, on before unload the page is still interacting, the return method is like a shortcut for return "confirm()", the return of the confirm however cannot be handled at all, so you can not really investigate the response of the user and decide upon it which way to go, the response is going to be immediately carried out as "yes" leave page, or "no" don't leave page...
Notice that you have already changed the source of the url to Google before you prompt user, this action, cannot be undone... unless maybe, you can setimeout to something like 5 seconds (but then if the user isn't quick enough it won't pick up his answer)
Edit: I've just made it a 5000 time lapse and it always goes to Yahoo! Never picks up the google change at all.
I can do something such as the following every 30 seconds to reload the page, and the backend logic will determine which session have been invalidated:
setInterval(function () {
location.reload()
}, 30000);
However, how would I only run this 30s location.reload() if the user is not active? For example, how banks will have a user-timeout if the user has not been active on the page (which only starts counting after the user is 'inactive'). How would this be done?
One way is to track mousemoves. If the user has taken focus away from the page, or lost interest, there will usually be no mouse activity:
(function() {
var lastMove = Date.now();
document.onmousemove = function() {
lastMove = Date.now();
}
setInterval(function() {
var diff = Date.now() - lastMove;
if (diff > 1000) {
console.log('Inactive for ' + diff + ' ms');
}
}, 1000);
}());
First define what "active" means. "Active" means probably, sending a mouse click and a keystroke.
Then, design your own handler for these situations, something like this:
// Reseting the reload timer
MyActivityWatchdog.prototype.resetReloadTimer = function(event) {
var reloadTimeInterval = 30000;
var timerId = null;
...
if (timerId) {
window.clearInterval(timerId);
}
timerId = window.setInterval( reload... , reloadTimeInterval);
...
};
Then, make sure the necessary event handler will call resetReloadTimer(). For that, you have to look what your software already does. Are there key press handlers? Are there mouse movement handlers? Without knowing your code, registering keypress or mousemove on document or window and could be a good start:
window.onmousemove = function() {
...
activityWatchdog.resetReloadTimer();
...
};
But like this, be prepared that child elements like buttons etc. won't fire the event, and that there are already different event handlers. The compromise will be finding a good set of elements with registered handlers that makes sure "active" will be recognized. E.g. if you have a big rich text editor in your application, it may be enough to register only there. So maybe you can just add the call to resetReloadTimer() to the code there.
To solve the problem, use window blur and focus, if the person is not there for 30 seconds ,it will go in the else condition otherwise it will reload the page .
setTimeout(function(){
$(window).on("blur focus", function(e) {
var prevType = $(this).data("prevType");
if (prevType != e.type) { // reduce double fire issues
switch (e.type) {
case "blur":
$('div').text("user is not active on page ");
break;
case "focus":
location.reload()
break;
}
}
$(this).data("prevType", e.type);
})},30000);
DEMO : http://jsfiddle.net/rpawdg6w/2/
You can check user Session in a background , for example send AJAX call every 30 - 60 seconds. And if AJAX's response will be insufficient (e.g. Session expired) then you can reload the page.
var timer;
function checkSession() {
$.ajax({
url : 'checksession.php',
success: function(response) {
if (response == false) {
location.reload();
}
}
});
clearTimeout(timer);
timer = setTimeout(checkSession,30 * 1000);
}
checkSession();
I have a function applied to setInterval function. When I minimize or change the focused window, then get back to the browser showing my web site, the browser plays everything that happened since i changed the focus to another window, in a very fast manner.
Is there a way to hold the animations, setintervals when window of focus in windows change ?
Thanks.
I found this post:
JavaScript / jQuery: Test if window has focus
for me it worked on google chrome but it could be that it doesn't work in some browsers.
Here is a fiddle to test:
http://jsfiddle.net/ScKbk/
His answer:
var window_focus;
$(window).focus(function() {
window_focus = true;
})
.blur(function() {
window_focus = false;
});
$(document).one('click',function() {
setInterval(function() { $('body').append('has focus? ' + window_focus + '<br>'); }, 1000);
});
Try this.
var handeler;
function ShowAnimation()
{
//SetInterval code
handeler = SetInterval(myfunction, 1000);
}
//clear the handler when not in use.
function Clearhandler()
{
ClearTimeout(handeler);
}
//call the above method on the onblur event of window.
$(window).focus(ShowAnimation(),Clearhandler());
Much like Getu.ch answer except this will only execute your "work" code if the window has focus (runs every 3 seconds). Not tested in all browsers but here is a link showing browser compatibility of window.focus / window.blur
(function($) {
var windowHasFocus = false;
$(window).focus(function() {
windowHasFocus = true;
});
$(window).blur(function () {
windowHasFocus = false;
});
setInterval(function() {
if(windowHasFocus) {
//Do your work
}
}, 3000);
});
There is a good example for doing long press in Javascript here: Long Press in JavaScript?
But it does not provide for knowing the duration of the press.
If I want to do different things based on the length of the press I cant use the pattern in that post.
I was trying to do something similar by saving current time in a variable on('mousedown')
and then calculating the time difference on('mouseup').
this works fine within a normal Javasript page in a "normal" browser.
However within my phonegap app something happens,
looks like the mouseup event is not being called if the finger is kept on the screen for a long duration (say 5 sec..).
Is this some native mobile browser behavior? Can I override it somehow?
I am using plain jQuery not jQuery mobile.
Any ideas anyone?
You could have a look at how the taphold and vmouseup (handleTouchEnd() line 752) events are implemented in jQuery mobile source code.
Since it is already tested and implemented I'd suggest to use jquery mobile instead of jquery and modify (since it already handles all the 'quirks' related each mobile browser), and change the code as you need.
You can check the time to identify Click or Long Press [jQuery]
function AddButtonEventListener() {
try {
var mousedowntime;
var presstime;
$("button[id$='" + buttonID + "']").mousedown(function() {
var d = new Date();
mousedowntime = d.getTime();
});
$("button[id$='" + buttonID + "']").mouseup(function() {
var d = new Date();
presstime = d.getTime() - mousedowntime;
if (presstime > 999/*You can decide the time*/) {
//Do_Action_Long_Press_Event();
}
else {
//Do_Action_Click_Event();
}
});
}
catch (err) {
alert(err.message);
}
}
Note that this solution is usefull if you do not use jQuery Mobile for some reason.
I used the article Fast Touch Event Handling and just added a piece of code
$.event.special.tap = {
distanceThreshold: 10,
timeThreshold: 350,
setup: function () {
var self = this,
$self = $(self);
// Bind touch start
$self.on('touchstart', function (startEvent) {
// Save the target element of the start event
var target = startEvent.target,
touchStart = startEvent.originalEvent.touches[0],
startX = touchStart.pageX,
startY = touchStart.pageY,
threshold = $.event.special.tap.distanceThreshold,
timeout,
expired = false;
function timerFired() {
expired = true;
}
function removeTapHandler() {
clearTimeout(timeout);
$self.off('touchmove', moveHandler).off('touchend', tapHandler).off('touchcancel', removeTapHandler);
};
function tapHandler(endEvent) {
removeTapHandler();
if (target == endEvent.target) {
if (expired) {
$.event.simulate('longtap', self, endEvent);
} else {
$.event.simulate('tap', self, endEvent);
}
}
};
// Remove tap and move handlers if the touch moves too far
function moveHandler(moveEvent) {
var touchMove = moveEvent.originalEvent.touches[0],
moveX = touchMove.pageX,
moveY = touchMove.pageY;
if (Math.abs(moveX - startX) > threshold || Math.abs(moveY - startY) > threshold) {
removeTapHandler();
}
};
// Remove the tap and move handlers if the timeout expires
timeout = setTimeout(timerFired, $.event.special.tap.timeThreshold);
// When a touch starts, bind a touch end and touch move handler
$self.on('touchmove', moveHandler).on('touchend', tapHandler).on('touchcancel', removeTapHandler);
});
}
};
So, now I have a tap and a longtap events