Search code examples
pythonpyqtwebrtcpyqt5qwebengineview

Grant access to Cam & Mic using Python for PyQt WebEngine


I am building a simple web app called from Python. I am using the below code. What is the easiest way to programatically grant access to the Cam & Mic when this page is loaded? I have only found C++ examples on the web and cannot find a way to do this within Python code.

from PyQt5.QtWidgets import QApplication
from  PyQt5.QtWebEngineWidgets import QWebEngineView
from PyQt5.QtCore import QUrl

app = QApplication([])

view = QWebEngineView()
view.load(QUrl("https://test.webrtc.org/"))
view.show()
app.exec_()

Solution

  • To give permission you must use the setFeaturePermission method of QWebEnginePage, but you must do it when the view asks you to do so when it emits the featurePermissionRequested signal, this will indicate the url and the feature.

    from PyQt5.QtWidgets import QApplication
    from PyQt5.QtWebEngineWidgets import QWebEngineView, QWebEnginePage
    from PyQt5.QtCore import QUrl
    
    class WebEnginePage(QWebEnginePage):
        def __init__(self, *args, **kwargs):
            QWebEnginePage.__init__(self, *args, **kwargs)
            self.featurePermissionRequested.connect(self.onFeaturePermissionRequested)
    
        def onFeaturePermissionRequested(self, url, feature):
            if feature in (QWebEnginePage.MediaAudioCapture, 
                QWebEnginePage.MediaVideoCapture, 
                QWebEnginePage.MediaAudioVideoCapture):
                self.setFeaturePermission(url, feature, QWebEnginePage.PermissionGrantedByUser)
            else:
                self.setFeaturePermission(url, feature, QWebEnginePage.PermissionDeniedByUser)
    
    app = QApplication([])
    
    view = QWebEngineView()
    page = WebEnginePage()
    view.setPage(page)
    view.load(QUrl("https://test.webrtc.org/"))
    view.show()
    app.exec_()