Provide a way for Javascript code in a Webview to invoke Python functions
- Dominant language
- Python
- Stars
- 5.4k
- Forks
- 827
- Avg merge
- 9h 45m
- Merged PRs (30d)
- 58
Description
### What is the problem or limitation you are having?
It is possible for Python to invoke Javascript code in a web view; however, it is not possible for a Javascript function to call back to Python code.
### Describe the solution you'd like
PyQt5 WebView not work in iOS or Android so I hope toga can realize this function
this is pyqt5 solution
**index.html:**
```html
Webview Demo
function callPython() {
alert(api.print('print from JavaScript!'));
}
Call Python Code print
```
**webview.py:**
```python
import os
from PyQt5.QtCore import QUrl
from PyQt5.QtWebKit import QWebSettings
from PyQt5.QtWebKitWidgets import QWebView, QWebPage
from PyQt5.QtWidgets import QWidget
from posmesh.platform import API
class WebPage(QWebPage):
def __init__(self, parent=None):
super(WebPage, self).__init__(parent)
self.api = API()
self.mainFrame().javaScriptWindowObjectCleared.connect(self.populateJavaScriptWindowObject)
def populateJavaScriptWindowObject(self):
self.mainFrame().addToJavaScriptWindowObject('api', self.api)
class Webview(QWidget):
def __init__(self, url="", parent=None):
super(Webview, self).__init__(parent)
self.view = QWebView(self)
self.view.setPage(WebPage())
self.view.settings().setAttribute(QWebSettings.LocalContentCanAccessRemoteUrls, True)
self.view.load(QUrl.fromLocalFile(os.getcwd() + url))
self.view.show()
```
**api.py**
```python
from PyQt5.QtCore import pyqtSlot as Slot, QObject
class API(QObject):
@Slot(str, result=str)
def print(self, msg):
print(msg)
return 'printed'
```
### Describe alternatives you've considered
Haven't found a WebView jsbridge solution across iOS, Android, windows, and Linux yet using python.
### Additional context
_No response_
Contributor guide
Research direction
Start by reviewing the issue's index.html, webview.py, and api.py examples, then identify Toga's existing WebView APIs and platform implementations that would need to participate. Done would mean JavaScript in a WebView can invoke Python functions across the requested platforms, with the supported interface and behavior made explicit.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- javascript, python
- Domain
- api, mobile-dev
- Issue type
- Feature
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Needs clarification
- Newbie friendliness
- 25/100