In normal App development, we can use code like this to load a Web page packaged within App Assets.

webview.loadUrl("file:///android_asset/index.html");
Copy the code

When Android implements this function, it does not use the Context of the WebView object to find Assets as we imagine. Instead, it backchecks the apK path of the currently installed application using the application’s ApplicationId. So it’s natural to find the host application installed. Assets of a plug-in are not found in the host apK. The reason for this design, I suspect, is that WebView rendering is in a separate process, so it is not convenient to get the current WebView object context.

As a plug-in framework, our goal is always to make as much code as possible that would normally run in a plug-in environment. This API is often used in business development, so its support is important.

While I haven’t done particularly extensive research, I haven’t seen any other plug-in frameworks that support this capability. So I’ll jump right into how Shadow supports this functionality without using a private API.

I was inspired by the “Web Offline Package” solution. In the “Web Offline package” scenario, clients can intercept HTTP requests locally and return them directly as local resources. By packaging some Web resources directly into the client, you can speed up Web loading with this technique. Therefore, we can apply AOP ideas to modify the file:///android_asset/ protocol in WebView loadUrl.

Therefore, the scheme is very simple. First, use Shadow Transform to replace all webViews used in the App with ShadowWebView. Override the loadUrl method of the ShadowWebView. Change the requested file:///android_asset/ protocol to http://android.asset/. You can then take the “Web offline package” approach and return the required Assets from the plug-in’s Assets to the request. The reason for switching from file to HTTP is that the ability to intercept local requests only supports HTTP.

About this part of the code, please check the com. Tencent. Shadow. Core. The runtime. ShadowWebView class implementation.

PS: I just found a file:///android_res protocol that we haven’t used in Google. Students who are interested can help implement it and participate in the open source construction of Shadow.