728x90

Flutter 앱에서 WebView를 사용해 웹페이지를 로드할 때, 보안 강화를 위해 HTTP로 시작하는 URL을 자동으로 HTTPS로 변환하여 로드하는 방법을 소개합니다.
배경
HTTP URL은 암호화되지 않아 보안에 취약할 수 있습니다. 따라서 가능한 경우 HTTPS를 사용하는 것이 좋습니다. 아래 예제는 HTTP URL을 HTTPS로 자동 변환하여 WebView에서 로드하는 방법을 구현합니다.
구현 단계
- WebViewController 생성 및 초기화
- navigationDelegate를 사용한 URL 가로채기
- HTTP URL을 HTTPS로 변환
- 변환된 URL로 WebView 로드
1. WebViewController 생성 및 초기화
먼저 WebViewController를 생성하고 초기화하는 코드를 작성합니다.
WebView(
initialUrl: '<http://example.com>',
javascriptMode: JavascriptMode.unrestricted,
gestureNavigationEnabled: true,
onWebViewCreated: (WebViewController webViewController) {
controller = webViewController;
_isWebViewInitialized = true;
_launchDeepLinkIfReady();
},
2. navigationDelegate를 사용한 URL 가로채기
navigationDelegate를 사용하여 모든 URL 요청을 가로채고, HTTP로 시작하는 URL을 HTTPS로 변환합니다.
navigationDelegate: (request) async {
print('navigate url : ${request.url}');
String newUrl = request.url.replaceFirst('http:', 'https:');
print('modified url : $newUrl');
// http로 시작하는 URL을 https로 변경해서 로드
if (request.url.startsWith('http:')) {
await controller.loadUrl(newUrl);
return NavigationDecision.prevent;
}
return NavigationDecision.navigate;
},
3. 변환된 URL로 WebView 로드
HTTP로 시작하는 URL을 HTTPS로 변경하고 WebView를 통해 로드하는 방법입니다. 만약 URL이 HTTP로 시작하면 HTTPS로 변환하고, 그렇지 않으면 요청된 URL을 그대로 로드합니다.
전체 코드
children: [
WebView(
initialUrl: snapshot.data!,
javascriptMode: JavascriptMode.unrestricted,
gestureNavigationEnabled: true,
onWebViewCreated: (WebViewController webViewController) {
controller = webViewController;
_isWebViewInitialized = true;
_launchDeepLinkIfReady();
},
navigationDelegate: (request) async {
print('navigate url : ${request.url}');
String newUrl = request.url.replaceFirst('http:', 'https:');
print('modified url : $newUrl');
// http로 시작하는 URL을 https로 변경해서 로드
if (request.url.startsWith('http:')) {
await controller.loadUrl(newUrl);
return NavigationDecision.prevent;
}
return NavigationDecision.navigate;
},
),
],
결론
이렇게 하면 Flutter WebView에서 HTTP URL을 HTTPS로 자동 변환하여 로드할 수 있습니다. 이를 통해 앱의 보안을 강화하고, 사용자에게 더 안전한 웹 브라우징 환경을 제공할 수 있습니다.
728x90
'Flutter' 카테고리의 다른 글
[Flutter] webview 이미지 전송하는 방법 (1) | 2024.06.27 |
---|---|
[Flutter] iOS 및 Android 알림 권한 요청하는 방법 (0) | 2024.06.26 |
댓글