Opening another window in Javascript when user presses X on browser - javascript

I understand this question has been asked and either answered or rejected before, but i promise i have a reasonably legit reason for asking. I am doing a Uni course and one of the requirements for the web app we are making is to have a certain page (daily sales report) open once the user presses X on the browser, this is a local file only ans aside from using window.onbeforeunload = window.open("dailyreport.html"); , which opens the page every time I do anything (click links etc) I have hit a brick wall.
Also i forgot to mention we are not allowd to use JSON or jquery at all... sucks but thats what the bosses want
Thanks guys
Steve

You are looking for the windown.onclose event.
As from here
However, note that this is not supported by all browsers. If it is for a uni project you might be able to get away with it though if your requirements don't specify across-the-board browser compatibility.

Try this JSFIDDLE
window.onload = function(){
var as = document.getElementsByTagName("a");
var linkClicked = false;
for(i=0;i<as.length; i++){
as[i].onclick = function(){
linkClicked= true;
}
}
window.onbeforeunload = function(){!linkClicked && window.open("dailyreport.html");}
}

Related

Struggling with onclick in mobile browser

I work for a hire company, and I decided paperwork was a pain and have started putting it online instead. I'm building a service/repair database to store records and information on machines on our fleet. We have a desktop pc in the workshop, connected to the internet, but we have had an ongoing issue with our phone lines dropping in and out for the last few years and despite us calling out engineers, they can't explain it. Anyway, long story short, I've made a 'backup' copy of the website and database on localhost using xampp. I made a simple script to detect if we were online or not and added it to an onclick event.
function conchecklink(link) {
var online = navigator.onLine;
var livelink = "http://www.example.com/workshop/" + link;
var locallink = "http://localhost/workshop/" + link;
if (online == true) {
window.location(livelink);
}
if (online == false) {
window.location(locallink);
}
}
For each href on the website I am using this:
<a onclick=\"conchecklink('service.php')\" href=\"#\"> Service</a>
<a onclick=\"conchecklink('repair.php')\" href=\"#\"> Repairs</a>
Now this works absolutely fine on desktop, when internet drops out, it redirects to localhost, and visa versa. But when viewing on my mobile, the onclick event doesn't fire. From googling this, I understand I should be using ontouch for mobile, I tried a few things I found in my search, but alas I am only a mechanic, not a professional coder and I can't get the links working on mobile. Any help would be much appreciated.
You have an error: window.location is not a function. On your mobile, the browser should throw an error and stops the script. Your desktop browser seems to be more conciliant.
You also could use else instead of using two if statements.
function conchecklink(link) {
var online = navigator.onLine;
var livelink = "http://www.example.com/workshop/" + link;
var locallink = "http://localhost/workshop/" + link;
if (online) window.location.href = livelink;
else window.location.href = locallink;
}
The way you have used window.location is wrong, it is not a function hence do not accept arguments.
you can use it like this window.location = URL;

How to Handle redirects in Node.JS with HorsemanJs and PhantomJS

I´ve recently started using horseman.js to scrap a page with node. I can´t figure out how exactly it works and I can´t find good examples on the internet.
My main goal is to log on a platform and extract some data. I´ve managed to do this with PhantomJS, but know I want to learn how to do it with horseman.JS.
My code should open the login page, fill the login and password inputs and click on the "login" button. Pretty easy so far. However, after clicking on the "login" button the site makes 2 redirects before loading the actual page where I want to work.
My problem is that I don´t know how to make my code wait for that page.
With phantomJS I had a workaround with the page URL. The following code shows how I´ve managed to do it with phantomJS and it works just fine:
var page = require('webpage').create();
var urlHome = 'http://akna.com.br/site/montatela.php?t=acesse&header=n&footer=n';
var fillLoginInfo = function(){
$('#cmpLogin').val('mylogin');
$('#cmpSenha').val('mypassword');
$('.btn.btn-default').click();
};
page.onLoadFinished = function(){
var url = page.url;
console.log("Page Loaded: " + url);
if(url == urlHome){
page.evaluate(fillLoginInfo);
return;
}
// After the redirects the url has a "sid" parameter, I wait for that to apear when the page loads.
else if(url.indexOf("sid=") >0){
//Keep struggling with more codes!
return;
}
}
page.open(urlHome);
However, I can´t find a way to handle the redirects with horseman.JS.
Here is what I´ve been trying with horseman.JS without any success:
var Horseman = require("node-horseman");
var horseman = new Horseman();
var urlHome = 'http://akna.com.br/site/montatela.php?t=acesse&header=n&footer=n';
var fillLoginInfo = function(){
$('#cmpLogin').val('myemail');
$('#cmpSenha').val('mypassword');
$('.btn.btn-default').click();
}
var okStatus = function(){
return horseman.status();
}
horseman
.open(urlHome)
.type('input[name="cmpLogin"]','myemail')
.type('input[name="cmpSenha"]','mypassword')
.click('.btn-success')
.waitFor(okStatus, 200)
.screenshot('image.png')
.close();
How do I handle the redirects?
I'm currently solving the same problem, and my best solution so far is to use the waitForSelector method to target something on the final page.
E.g.
horseman
.open(urlHome)
.type('input[name="cmpLogin"]','myemail')
.type('input[name="cmpSenha"]','mypassword')
.click('.btn-success')
.waitForSelector("#loginComplete")
.screenshot('image.png')
.close();
Of course you have to know the page you're waiting for to do this.
If you know there are two redirects, you can use the approach of .waitForNextPage() twice. A naive approach if you didn't know how many redirects to expect would be to chain these until a timeout is reached (I don't recommend this as it will be slow!),
Perhaps a cleverer way, you can also use on events to capture redirects, like .on('navigationRequested') or .on('urlChanged').
Although it doesn't answer your question directly, this link may help: https://github.com/ariya/phantomjs/issues/11507

How do i make a redirect a iPad user?

This has probably been answered before but i don't understand al the difficult research online so i ask it here And hope for a easy answer
<script type="text/javascript"> // <![CDATA[
if ((navigator.userAgent.indexOf('iPad') != -1)) {
location.replace = "http://www.joey-games.byethost4.com/games/";
} // ]]>
This does not redirect me.
var isiPad = navigator.userAgent.match(/iPad/i) != null;
//or by using
var ua = navigator.userAgent;
var isiPad = /iPad/i.test(ua)
You can find other related information in the following links:
http://fellowtuts.com/jquery/ipadiphone-detection-using-javascript/
Detect iPad users using jQuery?
Instead of using location.replace use location.href
Your snippet becomes
if (navigator.userAgent.indexOf('iPad') > -1) {
location.href = 'http://www.joey-games.byethost4.com/games/';
}
I've made two changes to your code
!= to > in the if statement which is no biggie (nothing relevant)
changed method call from replace to href Taken from MDN
The Location.replace() method replaces the current resource with the one at the provided URL. The difference from the assign() method is that after using replace() the current page will not be saved in session History, meaning the user won't be able to use the back button to navigate to it.
This basically says that if you use replace you cannot use the browsers back button to get to this page anymore, basically reducing the users user-experience since they'll get confused about what the back button does when they use your website.
This will redirect your users on the iPad to a different website however, you shouldn't do this - it's bad for your users and your website. (as partially explained above)
Iam Not gonna use The redirecting to go to "Joey-games.byethost4.com/games/" I wil redirect iPad users to: Joey-games.byethost4.com/mobile/iPad/ for a mobile site since flash player is not supported in safari yet

Chrome JavaScript location object

I am trying to start 3 applications from a browser by use of custom protocol names associated with these applications. This might look familiar to other threads started on stackoverflow, I believe that they do not help in resolving this issue so please dont close this thread just yet, it needs a different approach than those suggested in other threads.
example:
ts3server://a.b.c?property1=value1&property2=value2
...
...
to start these applications I would do
location.href = ts3server://a.b.c?property1=value1&property2=value2
location.href = ...
location.href = ...
which would work in FF but not in Chrome
I figured that it might by optimizing the number of writes when there will be effectively only the last change present.
So i did this:
function a ()
{
var apps = ['ts3server://...', 'anotherapp://...', '...'];
b(apps);
}
function b (apps)
{
if (apps.length == 0) return;
location.href = apps[0]; alert(apps[0]);
setTimeout(function (rest) {return function () {b(rest);};} (apps.slice(1)), 1);
}
But it didn't solve my problem (actually only the first location.href assignment is taken into account and even though the other calls happen long enough after the first one (thanks to changing the timeout delay to lets say 10000) the applications do not get started (the alerts are displayed).
If I try accessing each of the URIs separately the apps get started (first I call location.href = uri1 by clicking on one button, then I call location.href = uri2 by clicking again on another button).
Replacing:
location.href = ...
with:
var form = document.createElement('form');
form.action = ...
document.body.appendChild(form);
form.submit();
does not help either, nor does:
var frame = document.createElement('iframe');
frame.src = ...
document.body.appendChild(frame);
Is it possible to do what I am trying to do? How would it be done?
EDIT:
a reworded summary
i want to start MULTIPLE applications after one click on a link or a button like element. I want to achieve that with starting applications associated to custom protocols ... i would hold a list of links (in each link there is one protocol used) and i would try to do "location.src = link" for all items of the list. Which when used with 'for' does optimize to assigning only once (the last value) so i make the function something like recursive function with delay (which eliminates the optimization and really forces 3 distinct calls of location.src = list[head] when the list gets sliced before each call so that all the links are taken into account and they are assigned to the location.src. This all works just fine in Mozilla Firefox, but in google, after the first assignment the rest of the assignments lose effect (they are probably performed but dont trigger the associated application launch))
Are you having trouble looping through the elements? if so try the for..in statement here
Or are you having trouble navigating? if so try window.location.assign(new_location);
[edit]
You can also use window.location = "...";
[edit]
Ok so I did some work, and here is what I got. in the example I open a random ace of spades link. which is a custom protocol. click here and then click on the "click me". The comments show where the JSFiddle debugger found errors.

How to know if a page is currently being read by the user with Javascript?

I'm making a webpage with dynamic content that enters the view with AJAX polling. The page JS occasionally downloads updated information and renders it on the page while the user is reading other information. This sort of thing is costly to bandwidth and processing time. I would like to have the polling pause when the page is not being viewed.
I've noticed most of the webpages I have open spend the majority of their time minimized or in a nonviewed tab. I'd like to be able to pause the scripts until the page is actually being viewed.
I have no idea how to do it, and it seems to be trying to break out of the sandbox of the html DOM and reach into the user's system. It may be impossible, if the JS engine has no knowledge of its rendering environment. I've never even seen a different site do this (not that the user is intended to see it...)
So it makes for an interesting question for discussion, I think. How would you write a web app that is CPU heavy to pause when not being used? Giving the user a pause button is not reliable, I'd like it to be automatic.
Your best solution would be something like this:
var inactiveTimer;
var active = true;
function setTimer(){
inactiveTimer = setTimeOut("stopAjaxUpdateFunction()", 120000); //120 seconds
}
setTimer();
document.onmouseover = function() { clearTimeout ( inactiveTimer );
setTimer();
resumeAjaxUpdate();
}; //clear the timer and reset it.
function stopAjaxUpdateFunction(){
//Turn off AJAX update
active = false;
}
function resumeAjaxUpdate(){
if(active == false){
//Turn on AJAX update
active = true;
}else{
//do nothing since we are still active and the AJAX update is still on.
}
}
The stopAjaxUpdateFunction should stop the AJAX update progress.
How about setting an "inactivity timeout" which gets reset every time a mouse or keyboard event is received in the DOM? I believe this is how most IM programs decide that you're "away" (though they do it by hooking the input messages at the system-wide level)
I've looked at that problem before for a research project. At the time (2-3 years ago) I did not find a way to get information from the browser about whether or not you are minimized :(
First check when the window loses and gains focus.
window.onblur = function () { /* stop */ };
window.onfocus = function () { /* start */ };
Also, for various reasons, the user may stop reading the page without causing it to lose focus (e.g. he gets up and walks away from the computer). In that case, you have to assume after a period of inactivity (no mouse or keyboard events) that the users' attention has left the page. The code to do that is described in another answer.
I know you've already accepted an answer but I'd personally use a combination of several of the answers mentioned here for various reasons, including:
Using mouse events only alienates users proficient at keyboard based browsing.
Using blur/focus events don't allow for users who go make a cup of tea ;-)
I'd most likely use something like the following as a guideline:
var idleTimer, userIsIdle, pollingTimer;
document.onkeydown = document.onmousemove = resetTimer;
window.onload = function () {
pollingTimer = window.setTimeout(runPollingFunction, 30000);
resetTimer();
/* IE's onblur/onfocus is buggy */
if (window.navigator.appName == "Microsoft Internet Explorer")
document.onfocusin = resetTimer,
document.onfocusout = setIdle;
else
window.onfocus = resetTimer,
window.onblur = setIdle;
}
function resetTimer() {
if (userIsIdle)
setBack();
window.clearTimeout(idleTimer);
idleTimer = window.setTimeout(setIdle, 120000); // 2 minutes of no activity
}
function setIdle() {
userIsIdle = true;
window.clearTimeout(pollingTimer); // Clear the timer that initiates polling
window.clearTimeout(setIdle);
}
function setBack() {
userIsIdle = false;
runPollingFunction(); // call the polling function to instantly update page
pollingTimer = window.setTimeout(runPollingFunction, 300000);
}
You can listen for mousemove and keypress events. If one of those has been fired in the past X seconds, then continue with your updating. Otherwise, don't update.
It's not perfect, but I think it's the best you can do with pure JS.
If you want to venture into the world of Flash, Silverlight, or Java, you may be able to get more information from the browser.

Categories

Resources