flutter webview报错This request has been blocked; the content must be served over HTTPS.
时间: 2025-01-12 07:05:14 浏览: 1042
在Flutter中使用WebView时,如果遇到错误"This request has been blocked; the content must be served over HTTPS",这是因为现代浏览器和WebView都默认启用了安全策略,要求所有的请求必须通过HTTPS协议进行,而不是不安全的HTTP协议。
要解决这个问题,可以尝试以下几种方法:
1. **使用HTTPS**:确保你请求的资源是通过HTTPS协议提供的。将所有的资源链接从HTTP改为HTTPS。
2. **允许不安全的请求**:如果你无法使用HTTPS,可以在WebView的配置中设置允许不安全的请求。不过,这种方法不推荐在生产环境中使用,因为它会降低应用的安全性。
```dart
WebView(
initialUrl: 'http://example.com',
javascriptMode: JavascriptMode.unrestricted,
onWebViewCreated: (WebViewController webViewController) {
// 允许不安全的请求
webViewController.loadUrl('javascript:(function() {document.cookie = "cross-site-cookie=whatever; SameSite=None; Secure";})();');
},
)
```
3. **使用混合内容**:如果你使用的是混合内容(即在HTTPS页面中加载HTTP资源),可以通过配置WebView来允许混合内容。
```dart
import 'dart:io';
WebView(
initialUrl: 'https://example.com',
javascriptMode: JavascriptMode.unrestricted,
onWebViewCreated: (WebViewController webViewController) {
if (Platform.isAndroid) {
webViewController.loadUrl('javascript:(function() {document.cookie = "cross-site-cookie=whatever; SameSite=None; Secure";})();');
}
},
gestureNavigationEnabled: true,
)
```
4. **检查请求的URL**:确保你请求的URL是正确的,没有拼写错误或其他问题。
通过以上方法,你应该能够解决WebView中出现的"This request has been blocked; the content must be served over HTTPS"错误。
阅读全文
相关推荐














