I've searched the archives but not found anything specific to my query.
In JavaScript I have a function with a callback function that fires a request at a postcode API to get coordinates for a postcode.
const getPostCodeLatLng = (strPostCode, callback) => {
alert("used API"); // !!! DOESN'T ALERT ON MOBILE !!!
const request = new XMLHttpRequest();
request.addEventListener('readystatechange', () => {
if(request.readyState == 4){
const jsnPostCode=JSON.parse(request.responseText);
callback(jsnPostCode);}});
request.open('GET', 'http://api.getthedata.com/postcode/' + strPostCode);
request.send();
};
and
getPostCodeLatLng(strInputFieldValue, (jsnPostCode) => { // use the function to get data about the postcode and callback to this function
if(jsnPostCode.status=="match"){
alert("used API"); // !!! DOESN'T ALERT ON MOBILE !!!
let strPostCodeLatLng = "LatLng(" + jsnPostCode.data.latitude + ", "
+ jsnPostCode.data.longitude + ")";
setFieldswithLatLng(strPostCodeLatLng);
objDisplayFindCons.value=`Postcode: ${strInputFieldValue}`;}
else objDisplayFindCons.value=`No match found for Postcode: ${strInputFieldValue}`;})
The functions work fine on a desktop but didn't work on either a Samsung phone nor tablet. I'm using Chrome on all devices.
The second section of code is part of a larger section that responds to an event where data is entered into a text box, validated as a possible postcode (using regex) and then requested as per the first function. The JSON text response is then parsed and checked to see if a match was found (the server returns valid JSON for unfound postcodes).
I am clear that it all works fine until it encounters the function call getPostCodeLatLng() where it never runs either of the alert("used API") statements on mobile.
I am new to JavaScript and finding coding callback functions and events challenging but I can't see any obvious bugs/reasons for this to fail on mobiles.
Are there known problems or limitations to what I'm doing?
Is there a way to workaround this or debug it effectively on mobile?
Please help!
Thanks,
Phil
So I tried various things and found the issue to be with using a http request.
Apparently from now on all requests from a Chrome browser on Android need to be https.
So changing request.open('GET', 'http://api.getthedata.com/postcode/' + strPostCode);
to request.open('GET', 'https://api.getthedata.com/postcode/' + strPostCode); fixed the problem straightaway.
Here is an article mentioning the change:-
https://www.thesslstore.com/blog/https-will-now-be-the-default-for-all-android-p-apps/
You live and learn...
Related
I'm new to web development and am trying to build a small webpage that'll attempt to detect if anyone's currently logged into Instagram on that browser. If I run my code command-by-command in Chrome's console and manually copy-paste the HTML, it works perfectly. But when I try to run my code separately, it seems to run as if it was in Incognito mode.
How would one get around this? If the user needs to grant my page permission to access Instagram, how would I do that?
Here's the JS part of my code:
const USERNAME_REGEX = /"viewer"\:{.*"full_name"\:"([^"]+)"/gm;
const FULLNAME = 'full_name\":\"';
document.addEventListener('DOMContentLoaded', () => {
const request = new XMLHttpRequest();
request.open('GET', 'https://instagram.com');
request.send();
request.onload = () => {
const data = request.responseText;
var u = data.match(USERNAME_REGEX);
if (u != null) {
u = u[0];
u = u.substring(u.indexOf(FULLNAME) + FULLNAME.length).slice(0, -1);
document.querySelector('#info').innerHTML = u;
}
else {
document.querySelector('#info').innerHTML = 'no one is logged in!';
}
}
});
Thank you :) have a wonderful day!
I'm new to web development and am trying to build a small webpage that'll attempt to detect if anyone's currently logged into Instagram on that browser.
That sounds like a security and privacy nightmare, which fortunately for everyone (you included) isn't possible. (Or at least, it shouldn't be...)
If I run my code command-by-command in Chrome's console and manually copy-paste the HTML, it works perfectly.
Totally different context. You'll find, in fact, that if you run this code in a console that isn't on Instagram.com, it won't work.
Same-origin policy will prevent you from accessing another domain. What you're attempting is a classic cross-origin attack that isn't going to work. CORS would get around this, but Instagram surely isn't going to enable you access.
How would one get around this?
You don't.
I am using Websync3, Javascript API, and subscribing to approximately 9 different channels on one page. Firefox and Chrome have no problems, but IE9 is throwing an alert error stating The request is too large for IE to process properly.
Unfortunately the internet has little to no information on this. So does anyone have any clues as to how to remedy this?
var client = fm.websync.client;
client.initialize({
key: '********-****-****-****-************'
});
client.connect({
autoDisconnect: true,
onStreamFailure: function(args){
alert("Stream failure");
},
stayConnected: true
});
client.subscribe({
channel: '/channel',
onSuccess: function(args) {
alert("Successfully connected to stream");
},
onFailure: function(args){
alert("Failed to connect to stream");
},
onSubscribersChange: function(args) {
var change = args.change;
for (var i = 0; i < change.clients.length; i++) {
var changeClient = change.clients[i];
// If someone subscribes to the channel
if(change.type == 'subscribe') {
// If something unsubscribes to the channel
}else{
}
}
},
onReceive: function(args){
text = args.data.text;
text = text.split("=");
text = text[1];
if(text != "status" && text != "dummytext"){
//receiveUpdates(id, serial_number, args.data.text);
var update = eval('(' + args.data.text + ')');
}
}
});
This error occurs when WebSync is using the JSON-P protocol for transfers. This is mostly just for IE, cross domain environments. Meaning websync is on a different domain than your webpage is being served from. So IE doesn't want do make regular XHR requests for security reasons.
JSON-P basically encodes the up-stream data (your 9 channel subscriptions) as a URL encoded string that is tacked onto a regular request to the server. The server is supposed to interpret that URL-encoded string and send back the response as a JavaScript block that gets executed by the page.
This works fine, except that IE also has a limit on the overall request URL for an HTTP request of roughly 2kb. So if you pack too much into a single request to WebSync you might exceed this 2kb upstream limit.
The easiest solution is to either split up your WebSync requests into small pieces (ie: subscribe to only a few channels at a time in JavaScript), or to subscribe to one "master channel" and then program a WebSync BeforeSubscribe event that watches for that channel and re-writes the subscription channel list.
I suspect because you have a key in you example source above, you are using WebSync On-Demand? If that's the case, the only way to make a BeforeSubscribe event handler is to create a WebSync proxy.
So for the moment, since everyone else is stumped by this question as well, I put a trap in my PHP to not even load this Javascript script if the browser is Internet Destroyer (uhh, I mean Internet Explorer). Maybe a solution will come in the future though.
I'm running this app in an Android phone (Samsung Galaxy mini running on ANdroid 2.2). I'm using couchdb for my database and host it on cloudant.
On device ready, the app will make a get request to the https db server which contains feeds of data that i need to be displayed in my app. At first, it was working fine but when i try to post and add new data to my https db server, then trigger the get request method, the returned response from the server is still the same as before(the newly posted data was not included even though i checked my db server and saw that it was indeed saved). Then i tried to close and reopen the app again, which will then make a new instance of the get http request, but still, the response still is the same as the very first one and doesnt contain the new data that was added to the db server. Then, I tried to reinstall my app, then run the app again, and oddly enough, the response from the get request now contains the new data.. I don't know how that happens, and I'm not really experienced with REST api and javascript so I might be doing something obviously wrong. Here's a snippet of my code for the get request:
var getFeedsClient;
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
if (window.XMLHttpRequest) {
getFeedsClient=new XMLHttpRequest();
}
else {
getFeedsClient=new ActiveXObject("Microsoft.XMLHTTP");
}
try{
getFeedsRequest();
} catch(e)
{
alert("Error on device ready: "+e);
}
}//on Device Ready
function getFeedsRequest() {
getFeedsClient.onreadystatechange = getFeedsFunction;
getFeedsClient.open("GET","https://<username>.cloudant.com/te/_design/requestfeed/_view/all",true);
getFeedsClient.send();
}
function getFeedsFunction() {
alert(" readystate: "+getFeedsClient.readyState+", status: "+getFeedsClient.status);
if(getFeedsClient.readyState == 4 && getFeedsClient.status == 200 ) {
var data = JSON.parse(getFeedsClient.responseText);
console.log("RESPONSE FROM COUCHDB "+getFeedsClient.responseText);
console.log("JSON data "+data);
//at first the total rows is 2 but when a new data was added, the total rows should be three, but that was not the case
alert("rows: "+data.total_rows);
}
}
I ran into a similar issue last week of the device caching requests. I solved it by adding a dummy unique parameter to the link like below:
function getFeedsRequest() {
getFeedsClient.onreadystatechange = getFeedsFunction;
var link = "https://<username>.cloudant.com/te/_design/requestfeed/_view/all";
var unique = (new Date).getTime();
getFeedsClient.open("GET",link + '?' + unique,true);
getFeedsClient.send();
}
Paul Beusterien's solution below worked for me with the following caveat:
An android 4.0.4. phone did not need a unique URL, but the same code running on 2.2.2 did!
My application uses polling to update the status of a music player. I'm using setInterval to make an Ajax call every half a second to do this. It works on many browsers (Chrome,Firefox, Safari... ) except the Nook color's browser. When the page loads it updates the correct information, but after that it always loads the same information. This was confirmed using alert. Here's the original code
function getStatus() {
request = new XMLHttpRequest();
request.open("GET", SOME_URL, true);
request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
request.onreadystatechange = function () {
if (request.readyState === 4 && request.status === 200)
updateStatus(request.responseText);
};
request.send()
}
setInterval(getStatus, 500);
Any ideas why it is always loading the same info (the info it fetches initially) ?
Also: it only loads the most current information if you clear the cache. This Nook was rooted and also had Firefox and it would work just fine. It's the Nook native browser that is doing this (rooted or unrooted).
Internet Explorer has a weird quirk where it caches AJAX content. I imagine you are seeing the same issue in the Nook browser. The solution is to add a "cache buster" parameter, which is basically just a random parameter so the URL is treated freshly:
"SOME_URL?random=" + Math.random()
I have a basic html page which has links that point to different site. What I want to do is track the clicks. I am doing so by sending a 0 pixel image call on Click event of the link without returning false on click event.
The same works fine on all the browsers except Safari(on windows OS).
when a link is clicked using javascript I delay the redirect and send an image request over to the server and log the click on server side. I have tried increasing the delay but with no success... The trackers work gr8 on all the browsers except Safari which does not sent the request at all.
I dont know why but possibly its that safari waits for the complete js to be executed before making the request and after the whole js is executed it gets redirected....
=========================================================
<html>
<head>
<script type="text/javascript">
function logEvent(){
image = new Image(1,1);
image.onLoad=function(){alert("Loaded");};
image.onLoad=function(){alert("Error");};
image.src='http://#path_to_logger_php#/log.php?'+Math.random(0, 1000) + '=' + Math.random(0, 1000);
pauseRedirect(500);
}
function pauseRedirect(millis){
var date = new Date();
var curDate = null;
do {curDate = new Date();}
while(curDate-date < millis);
}
</script>
</head>
<body>
Site 1<br/>
Site 2<br/>
</body>
</html>
=========================================================
Code works in chrome, firefox, ie and Opera. Does not work on Safari only..... any clues....
I had the same issue with all WebKit browsers. In all others you only need to do new Image().src = "url", and the browser will send the request even when navigating to a new page. WebKit will stop the request before it's sent when you navigate to a new page right after. Tried several hacks that inject the image to the document and even force a re-paint through img.clientHeight. I really don't want to use event.preventDefault, since that causes a lot of headaches when a link has target="_blank", form submit, etc. Ended up using a synchronous XmlHttpRequest for browsers supporting Cross Origin Resource Sharing, since it will send the request to the server even though you don't get to read the response. A synchronous request has the unfortunate side-effect of locking the UI-thread while waiting for response, so if the server is slow the page/browser will lock up until it receives a response.
var supportsCrossOriginResourceSharing = (typeof XMLHttpRequest != "undefined" && "withCredentials" in new XMLHttpRequest());
function logEvent() {
var trackUrl = 'http://#path_to_logger_php#/log.php?'+Math.random(0, 1000) + '=' + Math.random(0, 1000);
if(supportsCrossOriginResourceSharing) {
xhrTrack(trackUrl);
} else {
imgTrack(trackUrl);
}
}
function xhrTrack(trackUrl) {
var xhr = new XMLHttpRequest();
xhr.open("GET", trackUrl, false);
xhr.onreadystatechange = function() {
if(xhr.readyState >= this.OPENED) xhr.abort();
}
try { xhr.send() } catch(e) {}
}
function imgTrack(trackUrl) {
var trackImg = new Image(1,1);
trackImg.src = trackUrl;
}