I am writing a small Python and WebKit app; I am using WebKit as the UI for my app.
What I want to do is to create an interactive element in WebKit (namely a combo box or a set of clickable regions) and when the user interacts with these elements I can call a Python callback to do some processing and then update the WebKit view with new information.
Here is an example of what I want to do:
- User is presented with a combo box of options (combo box displayed, I assume, using a HTML form in WebKit).
- When the combo box option is selected,
on_combo_selected()
is called in my Python script which then grabs some data. - The data is passed to WebKit and the view is updated.
How can I do this?
Ways to communicate from an embedded WebKit widget to the controlling Python program
Gtk or Qt:
window.status
from JavaScript; trap the corresponding event in Pythondocument.title
from JavaScript; trap the corresponding event in Pythonx-my-app:thing1/thing2/thing3
); trapnavigation-policy-decision-requested
event in Python and look at the URL that's being navigated to, and deal with it if it's your custom URL schemeQt only:
frame.addToJavaScriptWindowObject
to add a (specifically designed) Python object to the JavaScript global namespace; call methods on it from JavaScript. (See http://pysnippet.blogspot.com/2010/01/calling-python-from-javascript-in-pyqts.html for an example.)Methods which theoretically should work but in practice don't, very well
Ways to communicate from Python to JavaScript
webview.execute_script(js_code)
. Note that if you're passing variable values in with the JS, it's a good idea to JSON encode them; that way you can worry a bit less about escaping, and JS can read JSON nativelyHere's some example Gtk code:
It's been a while since I played with that but here's what I did:
Use something like
in your HTML. So when the user selects an item a
mycombo
-URI with the selected value is called. To catch this connect a handler to your WebView'snavigation-requested
signal:In your signal handler you check if the request is for a
mycombo
URI. If so callon_combo_selected
:To update your WebView use its
execute_script
function to run some JavaScript code that does the updates, like: