To allow Android Webview to visit camera, you need to override the onPermissionRequest method in your app:
Java
xxxxxxxxxxprivate var mWebChromeClient: WebChromeClient = object : WebChromeClient() {
override fun onPermissionRequest(request: PermissionRequest?) {
// IMPORTANT: Check host and adapt filter to allow camera access // e.g. if (request?.origin?.host == "xxx") {...}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { if (context is BaseActivity) { if (ContextCompat.checkSelfPermission( context, Manifest.permission.CAMERA ) == PackageManager.PERMISSION_GRANTED ) { request?.grant(request.resources) } else { context.requestPermission(Manifest.permission.CAMERA) { granted -> if (granted) { request?.grant(request.resources) } else { request?.deny() } } } } } }} To enable iOS Webview camera permission, you need the following adjustment:
Inside info.plist file, set NSCameraUsageDescription to allow the app to access camera.
XML
xxxxxxxxxx<key>NSCameraUsageDescription</key> <string>$(PRODUCT_NAME) need to use your rear camera</string> Config Webview instance to allow inline media playback, disable user action for playback, enable JavaScript, and enable JavaScript to automatically open windows.
Objective-C
xxxxxxxxxxlet configuration = WKWebViewConfiguration()configuration.allowsInlineMediaPlayback = trueconfiguration.mediaTypesRequiringUserActionForPlayback = []configuration.preferences.javaScriptEnabled = trueconfiguration.preferences.javaScriptCanOpenWindowsAutomatically = trueself.webView = WKWebView(frame: self.view.bounds, configuration: configuration)Before entering H5 Verfication Page, check and request for camera access first.
Swift
xxxxxxxxxx// 请求相机权限(swift 样例代码)// Request camera permission (in Swift)func checkAVAuthorizationStatus(with block: @escaping((_ authed: Bool) -> Void)) { let authStatus = AVCaptureDevice.authorizationStatus(for: .video) if authStatus == .authorized { block(true) } else if authStatus == .denied || authStatus == .restricted { block(false) } else { AVCaptureDevice.requestAccess(for: .video) { (result) in DispatchQueue.main.async { block(result) } } }}
// Usage// Check auth status before entering H5 webpage.self.checkAVAuthorizationStatus { authed in if authed { // Enter H5 webpage directly } else { // Logic to handle camera unauthorised. }}(Optional) To avoid camera permission prompt in H5 every time.
Swift
xxxxxxxxxx// Make sure your ViewController inherits WKUIDelegate.class ViewController: UIViewController, WKUIDelegate { ...
// Only verified for iOS 15+ @available(iOS 15.0, *) func webView(_ webView: WKWebView, requestMediaCapturePermissionFor origin: WKSecurityOrigin, initiatedByFrame frame: WKFrameInfo, type: WKMediaCaptureType, decisionHandler: @escaping (WKPermissionDecision) -> Void) { // NOTE: please add necessary security check like domain filter if needed. decisionHandler(.grant) }}
self.webView.uiDelegate = self