setTimeout not called in android webkit - javascript

On my android phone (2.1) I'm seeing a strange behavior with setTimeout when keeping a finger pressed on the touchscreen for a while.
This very simple code in fact works fine (1 call each second), until I scroll for a while the window (2-3 seconds are sufficient), when it stops being called
$(document).ready(function(){
spam();
});
function spam(){
console.log("cia")
setTimeout(spam, 1000);
}

I has the same Problem.
The solution was for me to define the called function as a variable, than passing ist as parameter to the setTimeout.
Try this:
var spam = function(){
console.log("cia")
setTimeout(spam, 1000);
}
$(document).ready(function(){
spam();
});

I had this issue before on my device when doing some development but neither of these solutions worked for me.
From the reading I did it's reasonably well documented that this does happens but seems to be no consistent way of resolving it.
What worked for me was closing the window I had my test site up down, clearing the cache, exiting the browser then opening task manager and shutting down the process. When I opened my browser again and went to my test site the standard code I had originally started working again.
My only guess is that the browser itself get's itself into some weird state where it doesn't run standard inbuilt browser functions (neither setTimeout() or setInterval() worked for me but both the javascript functions did exist).
I was testing with a Samsung Galaxy S running Android 2.1, I don't know if this will help anyone else but it's what worked for me.

try this
function spam(){
console.log("cia")
setTimeout("spam()", 1000);
}
setTimeout:
/**
#param {String|Function} vCode
#param {Number} iMillis
#return Number
*/
window.setTimeout = function(vCode,iMillis) {};

For me Varriotts answer didn't work ... the only way I could get setTimeout working on the Android phone i used for testing (running v 2.something) is by the following notation:
function foo() {}
window.setTimeout(foo, 200);
This looks weird, passing just the name of a function, but after hours of trying around, it was the only way it worked.

I tried this and it solved my problem.
setTimout(function(){aFunction(text);}, 200);

Related

NightwatchJS method .resizeWindow not working

A while back, I had an issue using the .maximizeWindow() from NightwatchJS. I was able to resolve this issue by using the following:
"chromeOptions" : {
"args" : ["start-maximized"]
},
However, this was more a work around than a fix. Currently, I need to resize the window, not just maximize it, and want to use the .resizeWindow() method. I also need this to work in browsers other than Chrome, so the above fix is inadequate. Below is my current setup in a test I am writing. This code worked fine in the past and just recently I noticed that the window was no longer resizing correctly. Any thoughts on why it might be failing? Note: this is written in Coffeescript, not JS.
module.exports = {
"Geoprocessing Commands and Assert Tests": (browser) ->
browser
.launchAs "anonymous"
.assert.title "<app name>"
.iFrameReady()
.frame 0, () ->
browser
.resizeWindow 1800, 1000
.pageDisplayed()
.pause 1000
...
.frameParent()
browser.end()
}

In newer versions of Firefox, is it still possible to override a web page's JS function?

I am writing an extension to override a web page's JS function, and started from this question, but the answer does not appear to work in Firefox 42 on Linux.
Next, I tried to use exportFunction as described in the documentation, but that also silently failed.
Inside package.json, I have added the following sesction.
"permissions": {
"unsafe-content-script": true
}
Here is my index.js file.
var self = require('sdk/self');
require("sdk/tabs").on("ready", fixGoogle);
function fixGoogle(tab) {
if (tab.url.indexOf("google.com") > -1) {
tab.attach({
contentScriptFile: self.data.url("google-script.js")
});
}
}
Here is my current data/google-script.js.
unsafeWindow.rwt=function(){};
Note that manually typing in rwt=function(){}; to the browser's console achieves the desired effect, as does using a bookmarklet (which requires clicking) but I am writing the plugin to get this automatically every time I use Google.
Is it possible to override the rwt page function using a Firefox extension? If so, what is the correct API to use?
read the documentation you've linked to, specifically the chapter titled Expose functions to page scripts - which links to exportFunction
function blah() {}
exportFunction(blah, unsafeWindow, {defineAs: 'rwt'});
It turns out that the issue is that the redefinition of the function rwt is racing against the original definition and winning. The original runs after and overrides the function I defined, thereby making it look like my redefinition had silently failed.
Once I realized that this was the problem, the easiest hack around it was to add a timeout to the redefinition inside data/google-script.js.
setTimeout(function() {
unsafeWindow.rwt=function(){};
}, 1000);
Thus, the orignal answer is still correct but simply failed to address the race condition.
Even though content scripts share the DOM, they are otherwise isolated from page scripts. As you correctly surmised, one can use unsafeWindow in Firefox to bypass this isolation.
Personally, I don't like the name of unsafeWindow for some reason ;)
Therefore I propose another way to do this: make use of the thing that's shared between these scopes, i. e. DOM.
You can create a page script from a content script:
var script = 'rwt=function()();';
document.addEventListener('DOMContentLoaded', function() {
var scriptEl = document.createElement('script');
scriptEl.textContent = script;
document.head.appendChild(scriptEl);
});
The benefit of this approach is that you can use it in environments without unsafeWindow, e. g. chrome extensions.

Call javascript function from objective C on orientation change

First off I would like to say I am an absolute Objective C novice.
I have been looking everywhere for a solution for this, but somehow I cannot seem to get it to work.
All I want is to run a Javascript function from Objective C when an orientation change event occurs, seeing how this is the only way to execute Javascript before the orientation change animation starts.
I have been able to get a NSLog to show when an orientation change occurs, but no matter what I try, I am unable to execute any Javascript. Not even a console.log() or an alert(), let alone the actual function I want to trigger.
Could anyone please save me another afternoon of trial and error?
SOLVED
Place this in didFinishLaunchingWithOptions (AppDelegate.m):
[[NSNotificationCenter defaultCenter] addObserver: self
selector: #selector(orientationDidChange:)
name: UIApplicationDidChangeStatusBarOrientationNotification
object: nil];
And this just below
- (void) orientationDidChange: (NSNotification *) note
{
[self.viewController.webView stringByEvaluatingJavaScriptFromString:#"hideContentsDuringOrientationChange();"];
}
You should be able to do this:
- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration {
[(UIWebView *)self.visibleViewController.view stringByEvaluatingJavaScriptFromString:#"someGlobalJSFunction();"];
}
Your reference to the UIWebView may have to change based on how your project is setup.
You can use didRotateFromInterfaceOrientation for an event after the rotation is complete. I've found this sometimes fires just a bit early for the JS to redraw, though. I fixed that by putting a short timeout in the JS function it calls.

Geolocation doesn't stop in Phonegap

When I run
window.onload = function () {
document.addEventListener("deviceready", getGeolocation);
}
function getGeolocation() {
navigator.geolocation.getCurrentPosition( successCallback, errorCallback, {maximumAge: 0});
}
or
function getGeolocation() {
watchGeoMarkerProcess = navigator.geolocation.watchPosition(updateCallback, errorCallback);
}
and then
function updateCallback(position) {
if (position.coords.accuracy < 100) {
navigator.geolocation.clearWatch(watchGeoMarkerProcess);
}
}
in my app on iOS 5 using phonegap it seems to get stuck, since the geolocation indicator-icon stays in the top bar and it never goes away, which I take to mean that the GPS doesn' get turned off. Also, sometimes I don't get any coords at all, throwing a time-out error.
I don't think there is anything wrong with the code since it works just fine as a webapp.
Any ideas?
navigator._geo is the 'real' implementation I believe. I've seen recent git commits where they are trying to over-ride navigator.geolocation but apparently failing on iOS. Looking at the phonegap source code gave me the idea to try the real call instead.
Here is the git commit:
http://mail-archives.apache.org/mod_mbox/incubator-callback-commits/201203.mbox/%3C20120307000809.B82AA5D82#tyr.zones.apache.org%3E
Here is another thread on the problem:
https://groups.google.com/forum/?fromgroups#!topic/phonegap/W32yYpV28W8
UPDATE: I have some measure of success now:
Edit your phonegap.js, comment out lines 3451-3453 which look like this:
__proxyObj(navigator.geolocation, navigator._geo,...
You will get an ugly permission alert.. but the location should work. The reasoning behind this change is that you will now use safari's location detection, not PhoneGaps.
UPDATE2: ..and the problem with PhoneGap turned out to be a conflict with another javascript library, in this case dragdealer.js. So double check for any suspicious variable names like "Location" or "Position" in any other javascript you are using. For some reason this conflict was not a problem on platforms other than iOS.
For what it's worth I have a same problem and these fixes did not work. But they may for you:
make sure you get the location after onDeviceReady() has been called
try using navigator._geo.getCurrentPosition
I had the same problem, although on Android.
Adding the enableHighAccuracy option caused it to start working:
navigator.geolocation.getCurrentPosition(onSuccess, onError, {enableHighAccuracy:true} );

Threads (or something like) in javascript

I need to let a piece of code always run independently of other code. Is there a way of creating a thread in javascript to run this function?
--why setTimeout doesn't worked for me
I tried it, but it runs just a single time. And if I call the function recursively it throws the error "too much recursion" after some time. I need it running every 100 milis (it's a communication with a embedded system).
--as you ask, here goes some code
function update(v2) {
// I removed the use of v2 here for simplicity
dump("update\n"); // this will just print the string
setTimeout(new function() { update(v2); }, 100); // this try doesn't work
}
update(this.v);
It throws "too much recursion".
I am assuming you are asking about executing a function on a different thread. However, Javascript does not support multithreading.
See: Why doesn't JavaScript support multithreading?
The Javascript engine in all current browsers execute on a single thread. As stated in the post above, running functions on a different thread would lead to concurrency issues. For example, two functions modifying a single HTML element simultaneously.
As pointed out by others here, perhaps multi-threading is not what you actually need for your situation. setInterval might be adequate.
However, if you truly need multi-threading, JavaScript does support it through the web workers functionality. Basically, the main JavaScript thread can interact with the other threads (workers) only through events and message passing (strings, essentially). Workers do not have access to the DOM. This avoids any of the concurrency issues.
Here is the web workers spec: http://www.whatwg.org/specs/web-workers/current-work/
A more tutorial treatment: http://ejohn.org/blog/web-workers/
Get rid of the new keyword for the function you're passing to setTimeout(), and it should work.
function update(v2) {
try {
dump("update\n");
} catch(err) {
dump("Fail to update " + err + "\n");
}
setTimeout(function() { update(v2); }, 100);
}
update(this.v);
Or just use setInterval().
function update(v2) {
try {
dump("update\n");
} catch(err) {
dump("Fail to update " + err + "\n");
}
}
var this_v = this.v;
setInterval(function() {update(this_v);}, 100);
EDIT: Referenced this.v in a variable since I don't know what the value of this is in your application.
window.setTimeout() is what you need.
maybe you should to view about the javascirpt Workers (dedicated Web Workers provide a simple means for web content to run scripts in background threads), here a nice article, which explain how this works and how can we to use it.
HTML5 web mobile tutororial
U can try a loop instead of recursivity

Categories

Resources