Struggling with onclick in mobile browser - javascript

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;

Related

Redirect only if user is online

I am currently having an Issue with a Clients Intranet.
We used to have a start-site where some js checks, wether the user is online or not, and if so that he is redirected to the home-page of our Intranet.
Now I am testing the compatibility with the new Microsoft EDGE and found out that the automatic redirect isn´t working anymore.
Do you have any ideas of how to check if the user has a valid internet connection and then redirect?
Current solution is:
var myImg = new Image();
myImg.src = "https://URL_of_our_intranet/images/blank.gif";
myImg.onload = myImgOnLoadHandler;
function myImgOnLoadHandler(e) {
window.location = "redirect-URL";
}
The whole Code is on each Users Local System and there is no JQuery-Solution possible as there is no JQ-Library available.
I would love to hear an easy and on EDGE working solution.
If there is an easy way to do so, please let me know - I am not a pro in Javascript..
Thanks!
Sam
The above comments are worth considering. This is a kludge, and is always going to be fragile. As mentioned in the comments, a major pitfall here is caching. That can be circumvented by appending a cache-busting string to the URL. I don't think this is the case, but it's also possible that some browsers won't load an image that isn't a member of a DOM, so it might be necessary to insert it into the DOM. The below snippet demonstrates both:
function myImgOnLoadHandler(e) {
console.log('Connected! redirecting...');
}
function maybeRedirect() {
var myImg = new Image();
myImg.onload = myImgOnLoadHandler;
myImg.src = '//i.imgur.com/Jz49oEp.gif?' + new Date().getTime();
myImg.style.display = 'none';
document.body.appendChild(myImg);
}
document.querySelector('button').addEventListener('click', maybeRedirect);
<button type="button">Click me</button>
The solution that perfectly worked for me, as we only use Internet Explorer (at least some use firefox, but Opera is not available on any client):
if (navigator.onLine) {
window.location.replace("https://www.google.de");
}
Thanks for your quick help!

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

Opening another window in Javascript when user presses X on browser

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");}
}

Javascript onclick not called on some computers

I have an VB.NET web page that calls a javascript function when a checkbox in a datagrid view is checked or unchecked. The code works fine on my computer and for a few more people. But for most of the people the javascript function is not called at all when they check or uncheck a checkbox. All of these computers are Windows 7 and using IE 9. I also checked the IE->Internet Options->Advanced tab and the settings are the same on these machines. At this point I am out of ideas on this and google doesn't return any helpful results. I would really appreciate if someone can help me resolve this issue. Here is the code for the javascript function if that helps.
function SelectLineItem(pRowIndex)
{
var vGridView=document.getElementById('dgvFSOView');
var vLen=vGridView.rows.length;
var i=parseInt(pRowIndex)+1;
var intcount;
var vtxtFcheckbox=vGridView.rows[parseInt(pRowIndex)].cells[0].getElementsByTagName("input")[0].id;
var vFCheckbox=document.getElementById(vtxtFcheckbox);
var browser=navigator.appName;
for(intcount=i;intcount<=vLen-1;intcount++)
{
if ((document.getElementById('hifCheck').value=="ALL") || (document.getElementById('hifCheck').value=="-1"))
{
var vtxtSONO=vGridView.rows[intcount].cells[3].innerText;
}
else if((document.getElementById('hifCheck').value!="ALL") || (document.getElementById('hifCheck').value=="-1"))
{
var vtxtSONO=vGridView.rows[intcount].cells[2].innerText;
}
if(vtxtSONO=="")
{
if ((document.getElementById('hifCheck').value=="ALL") || (document.getElementById('hifCheck').value=="-1"))
{
var vtxttocheckbox=vGridView.rows[intcount].cells[14].getElementsByTagName("input")[0].id;
}
else
{
var vtxttocheckbox=vGridView.rows[intcount].cells[13].getElementsByTagName("input")[0].id;
}
var vTCheckbox=document.getElementById(vtxttocheckbox);
if(vFCheckbox.checked==true)
{
vTCheckbox.checked=true;
}
else
{
vTCheckbox.checked=false;
}
}
else
{
return false;
}
}
}
This could potentially be an issues with the permissions the users have on their computers. Security settings have different levels of permissions which vary depending on how the user set up their machine.
If you are running the code locally (IE: double clicking a local .html file) you often need to enable Javascript before any javascript can run at all on the page. If it's hosted on a website (IE: www.example.com/mypage.asp) then this shouldn't be a problem.
How are you calling this function? You may also want to try using the developer tools built into IE to see if any errors are occurring, which would prevent your script from completing.
Utilizing a cross browser compatible framework like jQuery might help your checkbox change event trigger, but could be overkill depending on what how complicated your project is.
Checkboxes do not reliably trigger the click event. Bind your function to the checkboxes' change event instead.

Facebook appMobi debugging when theres no distinct error

I am working on a project in appMobi, and this project has recently reached it portion that is related to facebook. However there just seems to be soo many moving parts that its virtually impossible to tell whats going on with what where and how.. more so, when everything works in the emulator but not on a device, where there is no console, no error log, nothing to work with to try and figure out the issue.
The image below is the only error I get on my device. When attempting to communicate with facebook, through appMobi specific methods. I have litteraly copied and pasted there code trying to make this work cause I know once I can see this working and how its going to work I can then start building logic around something I actually want to do. That being a mute point at the moment. Anyway, when I run this same exact code in the emulator it works exactly as expected. But running it in Test Anywhere on the device itself seems to be where this conflict is coming in.
Soo I am wondering, has anyone had this issue before out there on stack? If so what did you do to fix it? Whats the work around? Whats the means of how you debugged it and came to the conclusion as I am sure I am going to run into similar problems down the road and debugging on the device is also a bonus.
my javascript currently:
document.addEventListener("appMobi.facebook.login",function(e){
if (e.success == true)
{ console.log("Facebook Log in Successful"); }
else
{ console.log("Unsuccessful Login"); }
},false);
function fbLoginCheckz()
{
try{
AppMobi.facebook.login('user_birthday,user_about_me,user_status,offline_access,publish_stream,publish_actions,email,read_friendlists,publish_checkins,create_event');
}catch(e){
alert("Error Caught [FB 1]: "+e.message);
}
}
document.addEventListener("appMobi.facebook.logout",function(e){
if (e.success == true)
{ console.log("Logged out of Facebook"); }
else
{ console.log("Unsuccessful Logout"); }
},false);
var facebookUserID = "me"; //me = the user currently logged into Facebook
document.addEventListener("appMobi.facebook.request.response",function(e) {
console.log("Facebook User Friends Data Returned");
if (e.success == true) {
var data = e.data.data;
var outHTML = "";
for (var r=0; r< data.length; r++) {
outHTML += "<img src='http://graph.facebook.com/" + data[r]["id"]
+ "/picture' info='" + data[r]["name"] + "' />";
}
$("#blah").empty().html(outHTML);
document.removeEventListener("appMobi.facebook.request.response");
}
},false);
my html:
<br><br>
<div id="blah"></div>
RELOAD<br>
LOGIN<br>
LOGOUT<br>
FRIENDS
There was a problem with the build system and the test containers. If you build an adHoc version of your software it should work. However, all my "test anywhere" helper applications also still have the bug for the time being.
There should be an update to the test containers shortly that should fix the problem. I'll try to post back here once they have been updated.

Categories

Resources