Search code examples
javascriptioscordovaweb-workerwkwebview

WKWebView web worker throws error "Dom Exception 18 returns an error."


I am writing an app using PhoneGap. I want to use javascript Web Worker. It works fine on Android. It also works on iOS with UIWebView.

I would like to use WKWebView in iOS 9. I tried to read the .txt files in a local folder successfully using cordova-plugin-file.

I have used the following tutorial: https://www.scirra.com/blog/ashley/25/hacking-something-useful-out-of-wkwebview

But this did not solve it...

new Worker ('js/tested.js');
Dom Exception 18 returns an error.
new Worker ('www/js/tested.js');
Dom Exception 18 returns an error.

I tried to specify the full path to worker javascript file, but I get the same error:

new Worker (file_path+'js/tested.js');
Dom Exception 18 returns an error.

So how to create the worker?


Solution

  • It worked!

    Web workers without a separate Javascript file?

            var worker_js = null;
    
            function fetchLocalFileViaCordova(filename, successCallback, errorCallback)
            {
                var path = cordova.file.applicationDirectory + "www/" + filename;
    
                window.resolveLocalFileSystemURL(path, function (entry)
                {
                    entry.file(successCallback, errorCallback);
                }, errorCallback);
            };
    
            function fetchLocalFileViaCordovaAsText(filename, successCallback, errorCallback)
            {
                fetchLocalFileViaCordova(filename, function (file)
                {
                    var reader = new FileReader();
    
                    reader.onload = function (e)
                    {
                        successCallback(e.target.result);
                    };
    
                    reader.onerror = errorCallback;
                    reader.readAsText(file);
    
                }, errorCallback);
            };
    
            fetchLocalFileViaCordovaAsText("js/worker.js", function (js_script) { // Worker WKWebView
                worker_js = window.URL.createObjectURL(
                    new Blob([js_script], { type: "text/javascript" })
                );
            });
    
            if (worker_js != null) {
                backgroundEngine = new Worker(worker_js);
            } else {
                backgroundEngine = new Worker("js/worker.js");
            }