I am trying to use Tesseract
in offline mode in my Ionic 4
app. In order to do it I have based my code on what is explained in this example, although it is done with Ionic 3
and what the Tesseract GitHub explains regarding offline mode.
First, I have put the Tesseract
files in the src\assets\lib
directory as follows (the tesseract-
prefix for the files has been added by me):
Next I created a service that basically creates a Tesseract offline mode instance as indicated in the above mentioned links:
const path = this.webview.convertFileSrc(this.file.applicationDirectory + 'www/assets/lib/');
this.tesseract = await Tesseract.create({
langPath: path + 'tesseract-',
corePath: path + 'tesseract-index.js',
workerPath: path + 'tesseract-worker.js',
});
Some notes on the code:
this.file
is a File
from '@ionic-native/file/ngx'
.convertFileSrc
is to avoid the unable to load resource
error you get when trying to load the Javascript files directly.this.file.listDir
the contents of this.file.applicationDirectory + 'www/assets/lib/'
I can see the Tesseract
files.Now, when I deploy this to an Android emulator (Pixel 2 API 28)
and try to call the function where this code is I get following error, as per the Chrome debugger:
FWIW, this is my environment:
Ionic:
ionic (Ionic CLI) : 4.12.0 (C:\Users\guillem.vicens\AppData\Roaming\nvm\v10.15.3\node_modules\ionic)
Ionic Framework : @ionic/angular 4.1.2
@angular-devkit/build-angular : 0.13.6
@angular-devkit/schematics : 7.2.4
@angular/cli : 7.3.6
@ionic/angular-toolkit : 1.4.1
Cordova:
cordova (Cordova CLI) : not installed
Cordova Platforms : android 8.0.0
Cordova Plugins : cordova-plugin-ionic-keyboard 2.1.3, cordova-plugin-ionic-webview 3.1.2, (and 6 other plugins)
System:
Android SDK Tools : 26.1.1 (C:\Users\myUser\AppData\Local\Android\Sdk)
NodeJS : v10.15.3 (C:\Program Files\nodejs\node.exe)
npm : 6.4.1
OS : Windows 10
What am I missing? What is the correct way to access the assets
folder?
I finally managed to solve my problem by using a non-calculated URL base.
I noticed that the tesseract-tesseract-js
file was being loaded from the following URL:
http://localhost/assets/lib/tesseract-tesseract.js
But none of the others were loaded. This made me think that the problem was somehow related to the internal use in Tesseract.js
of relative paths that collided with the webview security policies.
Changing my code to do following did the trick:
this.tesseract = await Tesseract.create({
langPath: 'http://localhost/assets/lib/tesseract-',
corePath: 'http://localhost/assets/lib/tesseract-index.js',
workerPath: 'http://localhost/assets/lib/tesseract-worker.js',
});
I will have to test this on real mobile phones and on iOS, but this answers my original question.