Phonegap and WebWorkers

Neaox picture Neaox · Feb 21, 2015 · Viewed 10.7k times · Source

I am trying to write a PhoneGap/Cordova app.

I am trying to do some of the more long running background stuff in Web Workers. However I am finding that some of the functionality is not available from within the Web Workers.

navigator.connection is available from within the main script but is undefined from within the web worker, same goes for navigator.geolocation.

I would also like to access an sql-lite database from within a web worker too.

Any ideas of how to do background operations like this from within PhoneGap/Cordova?

Any help anyone can give would be great.

Answer

Exos picture Exos · Mar 1, 2015

First you need to understand that the Worker is a new thread or process, and this does not include the window and document objects.

Cordova creates an interface between the webview and the native API. If you run in a worker, you don't have access to this API interface, therefore you cannot use plugins or the cordova core.

I tried to import the cordova.js script into a worker:

loadScript('../cordova.js');

But it throws an error when it does not find the window object. Finally, emulating the objects:

self.window = this;
self.window.document = this;
loadScript('../cordova.js');

The cordova's script throws "ReferenceError: promp is not defined".

On the other hand, you need to understand to, the communication between the WebView and the native code, are asynchronous. If you send a SQLite query for example, your JavaScript code are continuing runs, when the query is resolved, the API sends an event to the WebView and you runs your callback.

I use workers for example to encrypt data, because this process is too hard and causes blocking. But if you need to use cordova plugins, you won't have this problem.

There is an explanation to understand this.

For SQLite, I recommend you use Cordova-SQLitePlugin.

If you need your own hight-process, You can learn about how to make plugins: https://cordova.apache.org/docs/en/4.0.0/guide_hybrid_plugins_index.md.html

In the meantime, you can use workers and send and received data, but not with resources references. And note that using apis (like SQLite), this will be asynchronous and you don't need to open another process to perform them. You can just send the result to a worker and work it from there.