Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Failed to register a ServiceWorker with Cordova 10 #1693

Closed
3 tasks done
nonameShijian opened this issue Feb 5, 2024 · 6 comments
Closed
3 tasks done

Failed to register a ServiceWorker with Cordova 10 #1693

nonameShijian opened this issue Feb 5, 2024 · 6 comments

Comments

@nonameShijian
Copy link

nonameShijian commented Feb 5, 2024

Bug Report

Problem

When I use ServiceWorker, the browser gives an error:
TypeError: Failed to register a ServiceWorker for scope ('https://localhost/') with script ('https://localhost/service-worker.js'): An unknown error occurred when fetching the script.

What is expected to happen?

The browser successfully registered ServiceWorker

What does actually happen?

The browser gives an error:
TypeError: Failed to register a ServiceWorker for scope ('https://localhost/') with script ('https://localhost/service-worker.js'): An unknown error occurred when fetching the script.

Information

I used Cordova version 10.0 to create an offline web game, which provides the WebViewAssetLoader class to access local web pages using HTTPS URLs.
But for the convenience of users to replace files, I want this webpage to display files stored in the external directory of the phone. The directory address is equivalent to 'cordova.file.externalApplicationStorageDirectory', so I made some modifications to the source code of CordovaLib.
The webpage display was successful, but the registration of ServiceWorker failed. After debugging, I found that the shouldInterceptRequest method of the SystemWebViewClient class cannot intercept the registration of ServiceWorker. Perhaps this is the reason for the registration failure.
My service-worker.js is placed in the root directory of the external storage directory corresponding to the app, such as file:///storage/emulated/0/Android/data/(packageName)/service-worker.js

Command or Code

Modify 'java/org/apache/cordova/engine/SystemWebViewClient.java' in the CordovaLib folder as follows:

// Replace this sentence with all the following code
// InputStream is = parentEngine.webView.getContext().getAssets().open("www/" + path, AssetManager.ACCESS_STREAMING);

AssetManager assetManager =  parentEngine.webView.getContext().getAssets();
InputStream is;
// The path originally set by Cordova
String[] split = ("www/" + path).split("/");
// Get the folder where the original path is located
String[] newSplit = Arrays.copyOfRange(split, 0, split.length - 1);
// All files and folders in the folder where the original path is located
List<String> list = Arrays.asList(assetManager.list(String.join("/", newSplit)));
if (list.contains(split[split.length - 1])) {
        is = assetManager.open("www/" + path, AssetManager.ACCESS_STREAMING);
} else {
        File file = new File(
                parentEngine.webView.getContext().getExternalFilesDir(null).getParentFile(),
                path
        );
        is = new FileInputStream(file);
}

Environment, Platform, Device

Android 12, and Google Webview 118

Version information

Cordova 10.0.0,Android Studio

Checklist

  • I searched for existing GitHub issues
  • I updated all Cordova tooling to most recent version
  • I included all the necessary information above
@breautek
Copy link
Contributor

I used Cordova version 10.0 to create an offline web game, which provides the WebViewAssetLoader class to access local web pages using HTTPS URLs.
But for the convenience of users to replace files, I want this webpage to display files stored in the external directory of the phone. The directory address is equivalent to 'cordova.file.externalApplicationStorageDirectory', so I made some modifications to the source code of CordovaLib.

This is something I don't think is tested but does service workers work as expected while using internal storage (e.g. if you place your service worker in your www folder)?

I wouldn't expect external storage to work and there are security implications in launching scripts from external storage. Your scripts should be part of your android bundle.

While within the Android OS, android's permission model can restrict applications from accessing or modifying app-specific files on external storage, but the external storage could be on a removable medium and if that storage medium is inserted into another device, say a PC, the file contents of app-specific external files could be manipulated. Therefore applications should treat scripts on external storage as untrusted and unsafe code.

@nonameShijian
Copy link
Author

I used Cordova version 10.0 to create an offline web game, which provides the WebViewAssetLoader class to access local web pages using HTTPS URLs.
But for the convenience of users to replace files, I want this webpage to display files stored in the external directory of the phone. The directory address is equivalent to 'cordova.file.externalApplicationStorageDirectory', so I made some modifications to the source code of CordovaLib.

This is something I don't think is tested but does service workers work as expected while using internal storage (e.g. if you place your service worker in your www folder)?

I wouldn't expect external storage to work and there are security implications in launching scripts from external storage. Your scripts should be part of your android bundle.

While within the Android OS, android's permission model can restrict applications from accessing or modifying app-specific files on external storage, but the external storage could be on a removable medium and if that storage medium is inserted into another device, say a PC, the file contents of app-specific external files could be manipulated. Therefore applications should treat scripts on external storage as untrusted and unsafe code.

Just now, I placed 'service worker. js' in the' asset/www 'directory and called the same interface, but still prompted registration failure.
bd8f176879794d19b2354864a86155e7

I know that storing startup scripts from external sources does pose security risks, but the web framework used in the game has been in place for a long time and is difficult to modify. The purpose of opening extension interfaces in the game was to allow players to easily modify source code files to achieve the desired effect, and players also have a clear understanding of what modifying source files represents.

@breautek
Copy link
Contributor

Ok thank you, that confirms that it still doesn't work "out of the box".

Glanceful reading, I'm guessing it's because the native needs to handle service worker registration using ServiceWorkerClient[ServiceWorkerController], (https://developer.android.com/reference/android/webkit/ServiceWorkerController), and ServiceWorkerWebSettings.

Cordova doesn't currently do this. The good news is the above classes were added in API 24, which fits within our minimum API level, so if a PR can be crafted and tested then we could potentially roll it into our 13.x release.

However, to re-iterate the service worker registration should probably be in the origin and context of webview asset loader (e.g. https://localhost / internal storage). In fact, MDN states that service workers must be ran in a secure context, thus it needs to go through the webview asset loader and the asset loader must be configured to use the https protocol. Even if the security implications are ignored, there might be technical limitations in registrating the service worker from external storage.

@nonameShijian
Copy link
Author

Ok thank you, that confirms that it still doesn't work "out of the box".

Glanceful reading, I'm guessing it's because the native needs to handle service worker registration using ServiceWorkerClient[ServiceWorkerController], (https://developer.android.com/reference/android/webkit/ServiceWorkerController), and ServiceWorkerWebSettings.

Cordova doesn't currently do this. The good news is the above classes were added in API 24, which fits within our minimum API level, so if a PR can be crafted and tested then we could potentially roll it into our 13.x release.

However, to re-iterate the service worker registration should probably be in the origin and context of webview asset loader (e.g. https://localhost / internal storage). In fact, MDN states that service workers must be ran in a secure context, thus it needs to go through the webview asset loader and the asset loader must be configured to use the https protocol. Even if the security implications are ignored, there might be technical limitations in registrating the service worker from external storage.

Thank you for your help. Before that, I had not heard of the ServiceWorkerClient class. I'm going to test if it's usable now. In addition, my game project also needs to be compatible with old platform phones. Previously, I used Cordova 8 and Crosswalk. I plan to extract the code from Cordova 10 about WebviewAssetLoader settings and test it again

@nonameShijian
Copy link
Author

Ok thank you, that confirms that it still doesn't work "out of the box".

Glanceful reading, I'm guessing it's because the native needs to handle service worker registration using ServiceWorkerClient[ServiceWorkerController], (https://developer.android.com/reference/android/webkit/ServiceWorkerController), and ServiceWorkerWebSettings.

Cordova doesn't currently do this. The good news is the above classes were added in API 24, which fits within our minimum API level, so if a PR can be crafted and tested then we could potentially roll it into our 13.x release.

However, to re-iterate the service worker registration should probably be in the origin and context of webview asset loader (e.g. https://localhost / internal storage). In fact, MDN states that service workers must be ran in a secure context, thus it needs to go through the webview asset loader and the asset loader must be configured to use the https protocol. Even if the security implications are ignored, there might be technical limitations in registrating the service worker from external storage.

I used 'ServiceWorkerController' in the construction method of the 'SystemWebViewClient. java' file, and then 'ServiceWorker' was successfully registered. Thank you again for your help.

this.assetLoader = assetLoaderBuilder.build();

ServiceWorkerController swController = ServiceWorkerController.getInstance();
swController.setServiceWorkerClient(new ServiceWorkerClient() {
    // I don't know how to reuse this variable, so I wrote it twice
    private final WebViewAssetLoader assetLoader = assetLoaderBuilder.build();
    @Override
    public WebResourceResponse shouldInterceptRequest(WebResourceRequest request) {
        // Capture request here and generate response or allow pass-through
        return assetLoader.shouldInterceptRequest(request.getUrl());
    }
 });
ServiceWorkerWebSettings serviceWorkerWebSettings = swController.getServiceWorkerWebSettings();
serviceWorkerWebSettings.setAllowContentAccess(true);
serviceWorkerWebSettings.setAllowFileAccess(true);

@jcesarmobile
Copy link
Member

next major version of cordova-android will have the ServiceWorkerController enabled by default

#1696

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants