I'm trying to get the current longitude and latitude using Cordova/PhoneGap. But I'm getting this error on fail function:
Position retrieval timed out.
I have set the maximumAge to 5000 and timeout to 10000.
This is the Cordova code snippet I'm using:
getCurrentPosition:function(successCallback, errorCallback, options) {
argscheck.checkArgs('fFO', 'geolocation.getCurrentPosition', arguments);
options = parseParameters(options);
var timeoutTimer = {timer:null};
var win = function(p) {
clearTimeout(timeoutTimer.timer);
if (!(timeoutTimer.timer)) {
return;
}
var pos = new Position(
{
latitude:p.latitude,
longitude:p.longitude,
altitude:p.altitude,
accuracy:p.accuracy,
heading:p.heading,
velocity:p.velocity,
altitudeAccuracy:p.altitudeAccuracy
},
(p.timestamp === undefined ? new Date() : ((p.timestamp instanceof Date) ? p.timestamp : new Date(p.timestamp)))
);
geolocation.lastPosition = pos;
successCallback(pos);
};
var fail = function(e) {
clearTimeout(timeoutTimer.timer);
timeoutTimer.timer = null;
var err = new PositionError(e.code, e.message);
if (errorCallback) {
errorCallback(err);
}
};
if (geolocation.lastPosition && options.maximumAge && (((new Date()).getTime() - geolocation.lastPosition.timestamp.getTime()) <= options.maximumAge)) {
successCallback(geolocation.lastPosition);
} else if (options.timeout === 0) {
fail({
code:PositionError.TIMEOUT,
message:"timeout value in PositionOptions set to 0 and no cached Position object available, or cached Position object's age exceeds provided PositionOptions' maximumAge parameter."
});
} else {
if (options.timeout !== Infinity) {
timeoutTimer.timer = createTimeout(fail, options.timeout);
} else {
timeoutTimer.timer = true;
}
exec(win, fail, "Geolocation", "getLocation", [options.enableHighAccuracy, options.maximumAge]);
}
return timeoutTimer;
},
Everything seems to be ok. But it doesn't call successCallback function. I don't know what I'm doing wrong.
I don't know if you've solved this, and I don't see which options you are sending to the getCurrentPosition method, but i made it work on wp8.1 with these options:
{
timeout: 20000,
enableHighAccuracy: true,
maximumAge: 90000
}
Related
I have been trying to bypass the captcha but all efforts in vain.
I don't know which function triger and thus it move forward as there is no submit button on the website.
So it only moves forward to show Challenge completed screen when someone do solve it manually.
I am stuck on injecting token. Please Guide me what to do next because i am noob in javascript
here is few javascript functions which i thnk are cause of all this.
Please tell me how to trigger a callback function so it moves to next page. or Complete the Funcaptcha.
Thanks
var loadedCheck = 0;
function getAllUrlParams(e) {
var t = e ? e.split("?")[1] : window.location.search.slice(1),
a = {};
if (t)
for (var n = (t = t.split("#")[0]).split("&"), i = 0; i < n.length; i++) {
var o = n[i].split("="),
s = o[0],
r = void 0 === o[1] || o[1];
if (((s = s.toLowerCase()), "string" == typeof r && (r = r.toLowerCase()), s.match(/\[(\d+)?\]$/))) {
var l = s.replace(/\[(\d+)?\]/, "");
if ((a[l] || (a[l] = []), s.match(/\[\d+\]$/))) {
var c = /\[(\d+)\]/.exec(s)[1];
a[l][c] = r;
} else a[l].push(r);
} else a[s] ? (a[s] && "string" == typeof a[s] ? ((a[s] = [a[s]]), a[s].push(r)) : a[s].push(r)) : (a[s] = r);
}
return a;
}
function loadArkose() {
var e = getAllUrlParams(window.location.href);
"xbox_1" === e.uitheme
? navigator.__defineGetter__("userAgent", function () {
return "Xbox_Dark";
})
: "xbox_2" === e.uitheme
? navigator.__defineGetter__("userAgent", function () {
return "Xbox_Light";
})
: "win8wiz" === e.uitheme &&
navigator.__defineGetter__("userAgent", function () {
return "Win8Wiz";
});
var t = window.location.pathname.split("/"),
a = new ArkoseEnforcement({
public_key: t[1],
language: e.mkt,
target_html: "arkose",
callback: function () {
parent.postMessage(JSON.stringify({ eventId: "challenge-complete", payload: { sessionToken: a.getSessionToken() } }), "*");
},
loaded_callback: function () {
(frameHeight = document.getElementById("fc-iframe-wrap").offsetHeight),
(frameWidth = document.getElementById("fc-iframe-wrap").offsetWidth),
"xbox_1" === e.uitheme || "xbox_2" === e.uitheme ? a.enableDirectionalInput() : e.uitheme,
parent.postMessage(JSON.stringify({ eventId: "challenge-loaded", payload: { sessionToken: a.getSessionToken(), frameHeight: frameHeight, frameWidth: frameWidth } }), "*"),
(loadedCheck = 1);
},
onsuppress: function () {
parent.postMessage(JSON.stringify({ eventId: "challenge-suppressed", payload: { sessionToken: a.getSessionToken() } }), "*");
},
onshown: function () {
parent.postMessage(JSON.stringify({ eventId: "challenge-shown", payload: { sessionToken: a.getSessionToken() } }), "*");
},
});
}
window.addEventListener("message", function (e) {
try {
JSON.parse(e.data);
} catch (e) {
return;
}
var t = JSON.parse(e.data);
switch (t.eventId) {
case "challenge-left":
case "challenge-right":
case "challenge-down":
case "challenge-up":
case "challenge-proceed":
window.dispatchEvent(new CustomEvent("FunCaptcha-action", { detail: { action: t.payload.action } }));
}
});
var interval = setInterval(function () {
(frameHeight = document.getElementById("fc-iframe-wrap").offsetHeight),
(frameWidth = document.getElementById("fc-iframe-wrap").offsetWidth),
1 == loadedCheck && parent.postMessage(JSON.stringify({ eventId: "challenge-iframeSize", payload: { frameHeight: frameHeight, frameWidth: frameWidth } }), "*");
}, 3e3);
Well After trying alot i was unable to find solution but then suddenly anti-captcha api Services updated there extension.
So this method worked for me.
Get Registered on anti-captcha.com and get api
Download Extension from this page Download and set name anticaptcha
add extension to your selenium code through this code snippet.
co = Options()
co.add_extension(os.path.abspath('anticaptcha.crx'))
driver = webdriver.Chrome(options=co)
Now define function which will in inject api key into the extension.
def acp_api_send_request(driver, message_type, data={}):
message = {
'receiver': 'antiCaptchaPlugin',
# request type, for example setOptions
'type': message_type,
# merge with additional data
**data
}
return driver.execute_script("""
return window.postMessage({});
""".format(json.dumps(message)))
Now Before Going to load a website where you want to solve captcha first load any website just so api can be injected properly. call this above function like this. replace your api key with Your_API_KEY_HERE text.
acp_api_send_request(
driver,
'setOptions',
{'options': {'antiCaptchaApiKey':
'Your_API_KEY_HERE'}}
)
Everthing is perfect now just when captcha will load the script will automatically detect it and solve it and submit the form.
happy coding..
I'm trying to start desktop screen streaming from native client to web browser. When i start connection sdp exchange is ok and media streaming starts as it should. But data channel is immidiately fires "close" event. As i understand data channel should be created befoe sdp exchange and i set negotiate to false. So it should automaticly inform other peer about this channel and start data channel. but it's not in my case.
I tried many different ways like setting datachannel with options or peer connection with or without options.
Am i missing something ?
Following is code for initiator from web browser.
var pcConstraints = {};
var servers = {
//iceTransportPolicy: 'relay', // force turn
iceServers:
[
{ url: 'stun:stun.l.google.com:19302' },
{ url: 'stun:stun.stunprotocol.org:3478' },
{ url: 'stun:stun.anyfirewall.com:3478' }
]
};
var offerOptions = {
offerToReceiveAudio: 0,
offerToReceiveVideo: 1,
trickle: false
};
function startStream() {
console.log("startStream...");
remotestream = new RTCPeerConnection(servers, pcConstraints);
if (localstream) {
remotestream.addStream(localstream);
}
// optional data channel
dataChannel = remotestream.createDataChannel('testchannel', {});
setDataChannel(dataChannel);
remotestream.onaddstream = function (e) {
try {
console.log("remote media connection success!");
var vid2 = document.getElementById('vid2');
vid2.srcObject = e.stream;
vid2.onloadedmetadata = function (e) {
vid2.play();
};
var t = setInterval(function () {
if (!remotestream) {
clearInterval(t);
}
else {
Promise.all([
remotestream.getStats(null).then(function (o) {
var rcv = null;
var snd = null;
o.forEach(function (s) {
if ((s.type == "inbound-rtp" && s.mediaType == "video" && !s.isRemote) ||
(s.type == "ssrc" && s.mediaType == "video" && s.id.indexOf("recv") >= 0))
{
rcv = s;
}
else if((s.type == "outbound-rtp" && s.mediaType == "video" && !s.isRemote) ||
(s.type == "ssrc" && s.mediaType == "video" && s.id.indexOf("send") >= 0))
{
snd = s;
}
});
return dumpStat(rcv, snd);
})
]).then(function (s) {
statsdiv.innerHTML = "<small>" + s + "</small>";
});
}
}, 100);
} catch (ex) {
console.log("Failed to connect to remote media!", ex);
socket.close();
}
};
remotestream.onicecandidate = function (event) {
if (event.candidate) {
var ice = parseIce(event.candidate.candidate);
if (ice && ice.component_id == 1 // skip RTCP
//&& ice.type == 'relay' // force turn
&& ice.localIP.indexOf(":") < 0) { // skip IP6
console.log('onicecandidate[local]: ' + event.candidate.candidate);
var obj = JSON.stringify({
"command": "onicecandidate",
"candidate": event.candidate
});
send(obj);
localIce.push(ice);
}
else {
console.log('onicecandidate[local skip]: ' + event.candidate.candidate);
}
}
else {
console.log('onicecandidate: complete.')
if (remoteAnswer) {
// fill empty pairs using last remote ice
//for (var i = 0, lenl = localIce.length; i < lenl; i++) {
// if (i >= remoteIce.length) {
// var c = remoteIce[remoteIce.length - 1];
// var ice = parseIce(c.candidate);
// ice.foundation += i;
// c.candidate = stringifyIce(ice);
// remotestream.addIceCandidate(c);
// }
//}
}
}
};
remotestream.createOffer(function (desc) {
console.log('createOffer: ' + desc.sdp);
remotestream.setLocalDescription(desc, function () {
var obj = JSON.stringify({
"command": "offer",
"desc": desc
});
send(obj);
},
function (errorInformation) {
console.log('setLocalDescription error: ' + errorInformation);
});
},
function (error) {
alert(error);
},
offerOptions);
}
function setDataChannel(dc) {
dc.onerror = function (error) {
alert("DataChannel Error:", error);
};
dc.onmessage = function (event) {
alert("DataChannel Message:", event.data);
};
dc.onopen = function () {
dataChannel.send("Hello World!");
};
dc.onclose = function (error) {
alert("DataChannel is Closed");
alert(error.data)
};
}
I've built a series of timers that are designed to be started, paused and resumed on cue. Numbers update dynamically on my page when the timer ticks up. The issue I'm having is figuring out how to get the timer to start from where it left off before I paused it. I can get it to restart from scratch, but I unsure how to take the paused Date.now() value, and work it into the formula to display the correct value. It will be something stupid that I just cant figure out.
function ticking2(num) {
//IF TIMER IS PAUSED CANCEL THE ANIMATION FRAME
if (timerObjArray[num].paused == true) {
timerObjArray[num].restartTime = Date.now();
cancelAnimationFrame(id);
} else if (timerObjArray[num].paused == false) {
timerObjArray[num].initialTime = Date.now()
if (timerObjArray[num].restartTime != 0) {
//THIS IS THE LINE WHERE I AM HAVING TROUBLE
timerObjArray[num].milli = ((timerObjArray[num].initialTime - timerObjArray[num].initialDate) - (timerObjArray[num].initialTime - timerObjArray[num].restartTime)) / 1000;
} else {
timerObjArray[num].milli = ((timerObjArray[num].initialTime - timerObjArray[num].initialDate ) / 1000);
}
//THIS FUNCTION TAKES THE MS VALUE AND CONVERTS IT TO HH:MM:SS
convert(num, timerObjArray[num].milli * 1000);
id = requestAnimationFrame(function() {
ticking2(num);
});
}
}
Thanks for the help.
I don't have enough information so, I made a simple implementation. You can look at this to help determine what you're missing. You're welcome to use it.
Timer fiddle
Utility:
var timer = (function() {
let _timers = {};
let pub = {
start : function(id) {
if(!_timers[id]) _timers[id] = {on:true, intervals:[{start:new Date()}] };
else if(_timers[id].on) throw 'timer is already started: ' + id;
else {
_timers[id].on = true;
_timers[id].intervals.push({start:new Date()});
}
},
stop : function(id) {
if(!_timers[id]) throw 'timer does not exist, cannot be stopped: ' + id;
else if(!_timers[id].on) throw 'timer is already stopped: ' + id;
else {
_timers[id].on = false;
let interval = _timers[id].intervals[_timers[id].intervals.length -1];
interval.stop = new Date();
interval.total = interval.stop - interval.start;
}
},
read : function(id) {
if(!_timers[id]) throw 'timer does not exist, cannot be read: ' + id;
let total = 0;
for(let i=0; i<_timers[id].intervals.length; i++) {
if(_timers[id].intervals[i].total) total += _timers[id].intervals[i].total;
else total += (new Date()) - _timers[id].intervals[i].start;
}
return { intervals:_timers[id].intervals, total: total };
},
delete: function(id) {
if(!_timers[id]) throw 'timer does not exist, cannot be deleted: ' + id;
delete _timers[id];
}
};
return pub;
})();
Example usage:
$('.start').on('click', function(){
timer.start(123);
});
$('.stop').on('click', function(){
timer.stop(123);
});
$('.clear').on('click', function(){
timer.delete(123);
$('input').val('');
});
setInterval(function(){
let result = null;
try//obviously not a great pattern
{
result = timer.read(123);
} catch(ex){}
if(result) {
$('input').val(result.total);
}
}, 35);
I am ask to write a java script program that retrieve an api JSON record from and address and through websocket every single minute. The stream continues after 60 seconds. I am expected to return the respective stream retrieve and the stream from the previous retrieve . Below is my code
var obj=
{
seconds : 60,
priv : 0,
prevTick : '' ,
data : ''
}
function countTime()
{
obj.seconds --;
obj.priv ++;
var msg ;
if(obj.priv > 1)
{
obj.priv = 0;
obj.msg = null;
}
if(prop.seconds < 0)
{
msg = sock.open();
obj.msg = obj.msg + ", New Tick : " + msg.msg ;
setTimeout(countTime, 1000);
obj.seconds = 60;
}
}
var sock= new WebSocket('link');
sock.onopen = function(evt) {
ws.send(JSON.stringify({ticks:'string'}));
};
sock.onmessage = function(msg) {
var data = JSON.parse(msg.data);
return 'record update: %o'+ data ;
};
Please what is wrong with my code above ? It does not delay at all. The stream continues irrespective.
How about encapsulating the buffering behavior into a class?
function SocketBuffer(socket, delay, ontick) {
var messages = [], tickInterval;
socket.onmessage = function(msg) {
messages.push( JSON.parse(msg.data) );
};
function tick() {
if (typeof ontick !== "function") return;
ontick( messages.splice(0) );
}
this.pause = function () {
tickInterval = clearInterval(tickInterval);
};
this.run = function () {
if (tickInterval) return;
tickInterval = setInterval(tick, delay * 1000);
tick();
};
this.run();
}
Note that .splice(0) returns all elements from the array and empties the array in the same step.
Usage:
var link = new WebSocket('link');
link.onopen = function (evt) {
this.send( JSON.stringify({ticks:'string'}) );
};
var linkBuf = new SocketBuffer(link, 60, function (newMessages) {
console.log(newMessages);
});
// if needed, you can:
linkBuf.pause();
linkBuf.run();
Try this:
function countTime() {
var interval = 1000; // How long do you have to wait for next round
// setInterval will create infinite loop if it is not asked to terminate with clearInterval
var looper = setInterval(function () {
// Your code here
// Terminate the loop if required
clearInterval(looper);
}, interval);
}
If you use setTimeout() you don't need to count the seconds manually. Furthermore, if you need to perform the task periodically, you'd better use setInterval() as #RyanB said. setTimeout() is useful for tasks that need to be performed only once. You're also using prop.seconds but prop doesn't seem to be defined. Finally, you need to call countTime() somewhere or it will never be executed.
This might work better:
var obj=
{
seconds : 60,
priv : 0,
prevTick : '' ,
data : ''
}
function countTime()
{
obj.seconds --;
obj.priv ++; //I don't understand this, it will always be set to zero 3 lines below
var msg ;
if(obj.priv > 1)
{
obj.priv = 0;
obj.msg = null;
}
msg = sock.open();
obj.msg = obj.msg + ", New Tick : " + msg.msg;
obj.seconds = 60;
//Maybe you should do sock.close() here
}
var sock= new WebSocket('link');
sock.onopen = function(evt) {
ws.send(JSON.stringify({ticks:'string'}));
};
sock.onmessage = function(msg) {
var data = JSON.parse(msg.data);
return 'record update: %o'+ data ;
};
var interval = setInterval(countTime, 1000);
EDIT: finally, when you're done, just do
clearInterval(interval);
to stop the execution.
function checkMessages(user, password, callback) {
var page = require('webpage').create();
page.open('http://mywebpage.com', function (status) {
if (status === 'fail') {
console.log(user + ': ?');
} else {
page.evaluate(function (user, password) {
document.querySelector('input[name=username]').value = user;
document.querySelector('input[name=password]').value = password;
document.querySelector('button[name=yt0]').click();
}, user, password);
waitFor(function() {
return page.evaluate(function() {
var el = document.getElementById('fancybox-wrap');
if (typeof(el) != 'undefined' && el != null) {
return true;
}
return false;
});
}, function() {
var messageCount = page.evaluate(function() {
var el = document.querySelector('span[class=unread-number]');
if (typeof(el) != 'undefined' && el != null) {
return el.innerText;
}
return 0;
});
console.log(messageCount);
});
}
page.close();
callback.apply();
});
}
For some reason, I just can't get this to work. PhantomJS is complaining: "Error: cannot access member 'evaluate' of deleted QObject". Is it because I am having multiple page.evaluates?
PhantomJS is asynchronous. In this case waitFor() is asynchronous, so you need to close the page after you've done with it. You need to move
page.close();
callback.apply();
into the last function that will be executed which is the callback of waitFor(). You might want to change waitFor a little bit, so that there is another callback when the timeout is reached which is the error branch which also requires the page closing and callback:
function waitFor(testFx, onReady, timeOutMillis) {
var maxtimeOutMillis = timeOutMillis ? timeOutMillis : 3000,
start = new Date().getTime(),
condition = false,
interval = setInterval(function() {
if ( (new Date().getTime() - start < maxtimeOutMillis) && !condition ) {
condition = testFx();
} else {
var error = null;
if(!condition) {
error = "'waitFor()' timeout";
console.log(error);
} else {
console.log("'waitFor()' finished in " + (new Date().getTime() - start) + "ms.");
clearInterval(interval);
}
onReady(error);
}
}, 250);
};