Phonegap and WebWorkers

前端 未结 3 1887
旧时难觅i
旧时难觅i 2021-02-13 21:24

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 funct

3条回答
  •  闹比i
    闹比i (楼主)
    2021-02-13 21:45

    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.

提交回复
热议问题