How to load the URL in InAppbrowser within 20 secs? - javascript

I am working in a cordova project and I am very new to cordova.
In that I have an requirement is like I am calling a url in the InAppbrowser . If the network connection is very slow(i.e. 20Kbps/ 50Kbps) I have to show an alert that ’Network slow’. Here I am using the setTimeout function and also I am checking the internet connection. But my problem is if internet connection is there the setTimeout function also calling after 20 secs.
I want to check only if internet connection is slow or else once my InAppbrowser load with url my setTimeout function should not call. Could anypne please help to resolve this issue. My code is like this.....
if(cid == null){
curl = “some url”;
//ref = cordova.InAppBrowser.open(curl, '_blank', 'location=no,hardwareback=yes');
ref = cordova.InAppBrowser.open(curl, '_blank', 'location=no,hardwareback=yes');
setTimeout(function(){
//alert("Hello");
if( startEndedVar == true)
{
ref = cordova.InAppBrowser.open(curl, '_blank', 'location=no,hardwareback=yes');
}
else{
ref = cordova.InAppBrowser.open("settings.html", '_blank', 'location=no,hardwareback=yes');
}
}, 3000);
ref.addEventListener('loadstart', function() {
//alert('laoding started');
});
ref.addEventListener('loadstop', function() {
startEndedVar = true;
//alert('laoding ended');
});
ref.addEventListener('exit', function(event){
screen.orientation.lock('portrait').then(function(obj) {
console.log(obj);
}, function(obj) {
console.log(obj);
});
});
}
Thanks in advance

It's because you have the same order twice: ref = cordova.InAppBrowser.open(curl, '_blank', 'location=no,hardwareback=yes');. Thanks to the if and else your going to open a window in each mode, also your TimeOut is called aufer 30s and not after 20s.
I'm not sure if there are some deeper problems in the logic.

Related

Post a message to newly opened browser

I'm trying to post a message using the postMessage function to a browser that I've opened using window.open and while I've found a couple of articles explaining on how to do it:
Window.postMessage()
HTML5’s window.postMessage API
I just can't get it to work.
In my grid, when double clicking on a row, I call the following code:
var win = window.open('#Url.Action("Index", "StandaloneViewer")', '_blank',
'width=600,height=800,scrollbars=yes');
var domainOrigin = document.location.origin;
var message = 'My Message';
win.postMessage(message, domainOrigin);
and in my Index.cshtml, I've got the following:
$(document).ready(function () {
window.addEventListener('message', function (event) {
debugger;
var domainOrigin = document.origin;
var domainPath = document.location.href;
if (event.origin !== domainOrigin) return;
...
}, false);
});
I've also tried the same code in the load event:
$(window).on("load", function () {
window.addEventListener('message', function (event) {
debugger;
var domainOrigin = document.origin;
var domainPath = document.location.href;
if (event.origin !== domainOrigin) return;
...
}, false);
});
but to no avail! Any ideas what I may be missing? I've got the same scenario working just fine when sending a message to an iframe but I have a use case where I need to launch a separate browser and send a message to it.
I'm currently testing this on the latest version of Chrome.
Thanks.

Opening two instances of InAppBrowser (_system and _blank) prevents events from triggering

We’re currently developing an app with cordova and the InAppBrowser plugin. We're trying to spawn two different IAB instances at the same time. One with the _system browser and another with the _blank option.
The problem we have is that once we open the instance of _system browser, it seems we lose the reference to the previous browser. For this reason, the close event never triggers on the _blank IAB after the _system browser is closed.
This is how the actual code looks like.
// Opening iab main window
var ref = window.open(global.chat_mediador, '_blank','location=no,toolbar=yes');
var handleEvents = function(event) {
// Closing the iab window
if (event.url.match('#close')) {
ref.close();
}
// Trigger custom event
if (event.url.match('#openccard')) {
window.open('https://www.test.example.url.com?customerID=' + event.customerId, '_system', 'location=yes');
}
}
// InAppBrowser events
// This events are duplicated because loadstop works on android and
// loadstart works on ios.
ref.addEventListener('loadstart', handleEvents, false);
ref.addEventListener('loadstop', handleEvents, false);
// Removing the dialog when we close the chat
ref.addEventListener('exit', function(event) {
generali.dialog.close();
}, false);
As you can see we open the first url within the application with the _blank option. Then if in the child application a button is pressed we want to open an instance of a browser in the _system browser.
We’ve tried (without luck) to:
Have a separate reference for the _system browser.
window.open(global.url_ficha + customerId, '_system','location=no');
var cardsRef = window.open(
'https://www.test.example.url.com?customerID=' + customerId,
'_system',
'location=yes'
);
Trigger a custom event outside the reference of the _blank browser
if (event.url.match('openccard')) {
var customerId = event.url.split('openccard-')[1];
var evt = document.createEvent("Event");
evt.initEvent("openccard",true,true);
evt.customerId = customerId;
document.dispatchEvent(evt);
}
Anyone has an idea of what's happening?
It seems that you need to initialize the IAB each time you do a new window.open() if you don't do that the event listeners don't work.
If I use that code it works like a charm.
window.openIAB = function(url, target, options) {
var self = this;
var ref = window.open(url, target, options);
var handleChildEvents = function(ev) {
if (ref != undefined) {
// Closing the iab window
if (ev.url.match('#close')) {
ref.close();
ref = undefined;
}
// Opening card url with system browser
if (ev.url.match('#openccard')) {
var customerId = ev.url.split('#openccard-')[1];
self.ref2 = self.openIAB(
'https://www.test.com?customerID=' + customerId,
'_system',
'location=yes'
);
}
} else {
console.log('InAppBrowser has no reference');
}
};
ref.addEventListener('loadstart', handleChildEvents);
ref.addEventListener('loadstop', handleChildEvents);
ref.addEventListener('loaderror', function(ev) {
console.log('error while loading page');
ref.close();
ref = undefined;
});
ref.addEventListener('exit', function(ev) {
dialog.close();
});
return ref;
};

How to get current link in InnAppBrowser Cordova

Hi i'm working in Xcode v6.1, Cordova v3.7 , jquerymobile v1.4.5
I have a list in which i have urls of external sites. on clicking any site it will open innappbrowser, i want to navigate in innappbrowser page. for instance i am in index page and after clicking or registeration page how can i get the current url from InnAppBrowser. I know the innAppBrowser exit event but couldnt find current url. here the code
function innAppInit(_url) {
try {
app.Log('browser news link=' + _url);
if (_url == null) {
_url = 'http://apache.org';
}
var ref = window.open(encodeURI(_url), '_blank', 'location=no');
console.Dir(ref);
ref.addEventListener('loadstart', function(event) {
$('.ui-loader').hide();
});
ref.addEventListener('exit', function(event) {
alert('exit');
console.Dir(this);
// **how to get current url here;**
});
} catch (e) {
console.log(e);
}
}
You have it in the event of the loadstart, just take it:
var ref = window.open(encodeURI(_url), '_blank', 'location=no');
ref.addEventListener('exit', function()
{
alert(event.url); // here you have the URL
});
See Cordova docs for more info

using onbeforeunload event, url change on selecting stay on this page

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.

Javascript, window.addEventListener('blur') won't work

I would like to set a timeout javascript.
If the browser stays on browser, it redirect to fallbackLink.
If the browser loses the focus, it expire the timeout and doesn't redirect to fallbackLink
here is my script.
<script>
(function(){
var fallbackLink = '<?=$info['failed_url']?>'+window.location.search+window.location.hash;
var isiOS = navigator.userAgent.match('iPad') || navigator.userAgent.match('iPhone'),
isAndroid = navigator.userAgent.match('Android');
if (isiOS) {
document.getElementById('loader').src = '<?=$info['scheme']?>://'+window.location.search+window.location.hash;
}
var countdown = window.setTimeout(function (){
window.location.replace(fallbackLink);
}, 1000);
window.addEventListener("blur", function(){
window.clearTimeout(countdown)
}, false);
})();
</script>
Somehow it does redirect even though the browser is out of focus.
I need to stop to redirect when the screen doesn't focus on web browser.
Thank you.
Apparently the only way to handle blur event on window objects is using window.onblur.
You can try to keep old handlers doing this:
var concatFunctions = function(fn1, fn2){
return function(){
var args = Array.prototype.slice.call(arguments, 0);
try{
fn1.apply(this, args);
} catch(err) { console.error(err); }
fn2.apply(this, args);
};
};
window.onblur = concatFunction(window.onblur, function(){
// do your stuff
});

Categories

Resources