在用移動設備加載H5頁面時,一些公共資源如css,js,圖片等若是比較大時,就須要經過攔截網絡,改從本地資源加載。在Android原生WebView
中,咱們能夠在WebViewClient
中的shouldInterceptRequest
方法來攔截替換資源。
然而在Flutter中的WebView插件,無論是官方的webview_flutter,仍是flutter_webview_plugin都不支持加載本地資源。
慶幸的是webview_flutter
底層實現是基於WebView
(Android)和WKWebView
(iOS)。只要在官方webview_flutter上稍做修改,就能夠實現離線資源加載。javascript
github: github.com/iamyours/we…
pub: iwebview_fluttercss
首先咱們從webview_flutter
中下載最新Archive(當前使用0.3.15+1
)。 解壓後,使用AndroidStudio打開,右鍵工程目錄,使用Android模式打開 java
若是要實現WebView
請求攔截,就必須給webView設置WebViewCilent
,全局搜索setWebViewClient
找到只有一處實現:android
//FlutterWebView.java
private void applySettings(Map<String, Object> settings) {
for (String key : settings.keySet()) {
switch (key) {
...
case "hasNavigationDelegate":
final boolean hasNavigationDelegate = (boolean) settings.get(key);
final WebViewClient webViewClient =
flutterWebViewClient.createWebViewClient(hasNavigationDelegate);
webView.setWebViewClient(webViewClient);
break;
...
}
}
}
複製代碼
經過以上代碼咱們知道具體邏輯在createWebViewClient
方法中:git
WebViewClient createWebViewClient(boolean hasNavigationDelegate) {
this.hasNavigationDelegate = hasNavigationDelegate;
if (!hasNavigationDelegate || android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
return internalCreateWebViewClient();
}
return internalCreateWebViewClientCompat();
}
複製代碼
而後在internalCreateWebViewClient
和internalCreateWebViewClientCompat
添加shouldInterceptRequest
方法,而後參照onPageFinished
在FlutterWebViewClient
加入shouldInterceptRequest
方法:github
private WebViewClient internalCreateWebViewClient() {
return new WebViewClient() {
...
@Override
public void onPageFinished(WebView view, String url) {
FlutterWebViewClient.this.onPageFinished(view, url);
}
...//參照
@Override
public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
WebResourceResponse response = FlutterWebViewClient.this.shouldInterceptRequest(view, url);
if (response != null) return response;
return super.shouldInterceptRequest(view, url);
}
};
}
複製代碼
咱們在shouldInterceptRequest
中接收來自Flutter世界的數據,如assets
中的二進制數據。可是要注意的是經過MethodChannel
接收數據是經過異步回調的形式,可是shouldInterceptRequest
方法須要同步接收數據,所以須要一個異步變同步
的執行器,同時MethodChannel
調用必須在主線呈調用。方法有不少,我這裏經過CountDownLatch
實現。web
public class SyncExecutor {
private final CountDownLatch countDownLatch = new CountDownLatch(1);
Handler mainHandler = new Handler(Looper.getMainLooper());
WebResourceResponse res = null;
public WebResourceResponse getResponse(final MethodChannel methodChannel, final String url) {
res = null;
mainHandler.post(new Runnable() {
@Override
public void run() {
methodChannel.invokeMethod("shouldInterceptRequest", url, new MethodChannel.Result() {
@Override
public void success(Object o) {
if (o instanceof Map) {
Map<String, Object> map = (Map<String, Object>) o;
byte[] bytes = (byte[]) map.get("data");
String type = (String) map.get("mineType");
String encode = (String) map.get("encoding");
res = new WebResourceResponse(type, encode, new ByteArrayInputStream(bytes));
}
countDownLatch.countDown();
}
@Override
public void error(String s, String s1, Object o) {
res = null;
countDownLatch.countDown();
}
@Override
public void notImplemented() {
res = null;
countDownLatch.countDown();
}
});
}
});
try {
countDownLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
return res;
}
}
複製代碼
注意到這裏success
中接收到Map
數據,咱們會在接下來Flutter
層傳過來。bash
在webview_method_channel.dart
中咱們找到了onPageFinished
接收來自Android或iOS的調用。參照onPageFinished
方法,咱們加入shouldInterceptRequest
方法,一樣的在_platformCallbacksHandler
對應的類中加入shouldInterceptRequest
方法。依次向上層類推。markdown
Future<dynamic> _onMethodCall(MethodCall call) async {
switch (call.method) {
case 'onPageFinished':
_platformCallbacksHandler.onPageFinished(call.arguments['url']);
return null;
case 'shouldInterceptRequest':
String url = call.arguments;
var response = await _platformCallbacksHandler.shouldInterceptRequest(url);
if (response != null) {
return {"data": response.data, "mineType": response.mineType, "encoding": response.encoding};
}
return null;
}
複製代碼
//webview_method_channel.dart
abstract class WebViewPlatformCallbacksHandler {
...
void onPageFinished(String url);
/// iamyours:Invoked by [WebViewPlatformController] when a request url intercepted.
Future<Response> shouldInterceptRequest(String url);
}
複製代碼
//webview_method_channel.dart
class Response {
final String mineType;
final String encoding;
final Uint8List data;
Response(this.mineType, this.encoding, this.data);
}
typedef void PageFinishedCallback(String url);
/// iamyours Signature for when a [WebView] interceptRequest .
typedef Future<Response> ShouldInterceptRequestCallback(String url);
class WebView extends StatefulWidget {
...
const WebView({
...
this.onPageFinished,
this.shouldInterceptRequest,
...,
})
class _WebViewState extends State<WebView> {
...
@override
void onPageFinished(String url) {
if (_widget.onPageFinished != null) {
_widget.onPageFinished(url);
}
}
...
@override
Future<Response> shouldInterceptRequest(String url) async{
if (_widget.shouldInterceptRequest != null) {
return _widget.shouldInterceptRequest(url);
}
return null;
}
}
複製代碼
而後咱們在example
中實現一個簡單的logo替換效果網絡
WebView(
initialUrl: "https://wap.sogou.com/",
javascriptMode: JavascriptMode.unrestricted,
debuggingEnabled: true,
onProgressChanged: (int p){
setState(() {
progress = p/100.0;
});
},
backgroundColor: Colors.red,
shouldInterceptRequest: (String url) async {//替換搜狗搜索logo爲baidu
var googleLogo = "https://wap.sogou.com/resource/static/index/images/logo_new.6f31942.png";
print("============url:$url");
if (url == googleLogo) {
ByteData data = await rootBundle.load("assets/baidu.png");
Uint8List bytes = Uint8List.view(data.buffer);
return Response("image/png", null, bytes);
}
return null;
},
),
複製代碼
webview_flutter
iOS端是基於WKWebview
實現的,攔截請求經過NSURLProtocol
實現,能夠參照iOS WKWebView (NSURLProtocol)攔截js、css,圖片資源一文。此法攔截是全局攔截的,因此須要一個全局變量存儲全部的FlutterMethodChannel
,這裏定義一個單例存儲這些數據。
//FlutterInstance.h
#import <Foundation/Foundation.h>
#import <Flutter/Flutter.h>
NS_ASSUME_NONNULL_BEGIN
@interface FlutterInstance : NSObject
@property(nonatomic,retain)NSMutableDictionary *channels;
+(FlutterInstance*)get;
+(FlutterMethodChannel*)channelWithAgent:(NSString*)agent;
+(void)removeChannel:(int64_t)viewId;
@end
NS_ASSUME_NONNULL_END
複製代碼
這裏爲了區分對應的請求是在哪一個channel
下的,咱們在給相應的WKWebview
的agent
最後加入#_viewId
//
// FlutterInstance.m
#import "FlutterInstance.h"
@implementation FlutterInstance
static FlutterInstance *instance = nil;
+(FlutterInstance *)get
{
@synchronized(self)
{
if(instance==nil)
{
instance= [FlutterInstance new];
instance.channels = [NSMutableDictionary dictionary];
}
}
return instance;
}
+(FlutterMethodChannel*)channelWithAgent:(NSString*)agent{
NSRange range = [agent rangeOfString:@"#" options:NSBackwardsSearch];
NSLog(@"range:%d,%d",range.length,range.location);
NSString *key = [agent substringFromIndex:range.location+1];
NSDictionary *channels = [self get].channels;
FlutterMethodChannel *channel = (FlutterMethodChannel*)[channels objectForKey:key];
return channel;
}
+(void)removeChannel:(int64_t)viewId{
NSMutableDictionary *channels = [self get].channels;
NSString *key = [NSString stringWithFormat:@"%lld",viewId];
[channels removeObjectForKey:key];
}
@end
複製代碼
咱們在WKWebview
的loadUrl
中修改userAgent
區分各個WebView對應的viewId
。
//FlutterWebView.m
- (bool)loadUrl:(NSString*)url withHeaders:(NSDictionary<NSString*, NSString*>*)headers {
NSURL* nsUrl = [NSURL URLWithString:url];
if (!nsUrl) {
return false;
}
NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:nsUrl];
NSString *vid = [NSString stringWithFormat:@"%lld",_viewId];
[_webView evaluateJavaScript:@"navigator.userAgent" completionHandler:^(id result, NSError *error) {
NSString *fixAgent = [NSString stringWithFormat:@"%@#%d",result,_viewId];
[_webView setCustomUserAgent:fixAgent];
}];
[_webView loadRequest:request];
return true;
}
複製代碼
而後在NSURLProtocol
協議中的startLoading
方法實現請求攔截
// FlutterNSURLProtocol.h
#import <Foundation/Foundation.h>
#import <Flutter/Flutter.h>
NS_ASSUME_NONNULL_BEGIN
@interface FlutterNSURLProtocol : NSURLProtocol
@end
NS_ASSUME_NONNULL_END
複製代碼
// FlutterNSURLProtocol.m
- (void)startLoading
{
NSMutableURLRequest *mutableReqeust = [[self request] mutableCopy];
//給咱們處理過的請求設置一個標識符, 防止無限循環,
[NSURLProtocol setProperty:@YES forKey:KFlutterNSURLProtocolKey inRequest:mutableReqeust];
NSString *agent = [mutableReqeust valueForHTTPHeaderField:@"User-Agent"];
FlutterMethodChannel *channel = [FlutterInstance channelWithAgent:agent];
if(channel==nil){
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:nil];
self.task = [session dataTaskWithRequest:self.request];
[self.task resume];
return;
}
[channel invokeMethod:@"shouldInterceptRequest" arguments:url result:^(id _Nullable result) {
if(result!=nil){
NSDictionary *dic = (NSDictionary *)result;
FlutterStandardTypedData *fData = (FlutterStandardTypedData *)[dic valueForKey:@"data"];
NSString *mineType = dic[@"mineType"];
NSString *encoding = dic[@"encoding"];
if([encoding isEqual:[NSNull null]])encoding = nil;
NSData *data = [fData data];
NSURLResponse* response = [[NSURLResponse alloc] initWithURL:self.request.URL MIMEType:mineType expectedContentLength:data.length textEncodingName:encoding];
[self.client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageAllowed];
[self.client URLProtocol:self didLoadData:data];
[self.client URLProtocolDidFinishLoading:self];
}else{
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:nil];
self.task = [session dataTaskWithRequest:self.request];
[self.task resume];
}
}];
}
複製代碼
經過以前設置的userAgent
獲取相應的FlutterMethodChannel
,調用shouldInterceptRequest
方法獲取Flutter
數據,經過Xcode
調試,咱們知道相應的byte數據類型爲FlutterStandardTypedData
。或者參照下圖:
實現google搜索logo替換
由於以前作了玩Android客戶端kotlin版,適配各個站點文章黑夜模式,須要替換相關css資源,所以纔會想到改造webview_flutter
插件,下面是flutter版本替換掘金文章css文件產生的黑夜模式效果