Answers:
从嵌入式WebKit小部件与控制Python程序进行通信的方式
Gtk或Qt:
window.status
从JavaScript 设置;在Python中捕获相应的事件document.title
从JavaScript 设置;在Python中捕获相应的事件x-my-app:thing1/thing2/thing3
);navigation-policy-decision-requested
在Python中捕获事件,并查看要导航到的URL,如果这是您的自定义URL方案,则对其进行处理仅Qt:
frame.addToJavaScriptWindowObject
将(专门设计的)Python对象添加到JavaScript全局名称空间;从JavaScript调用方法。(有关示例,请参见http://pysnippet.blogspot.com/2010/01/calling-python-from-javascript-in-pyqts.html。)从理论上讲应该可行但实际上却不可行的方法
从Python到JavaScript的通讯方式
webview.execute_script(js_code)
。请注意,如果您要通过JS传递变量值,则对它们进行JSON编码是一个好主意。这样,您就不必担心转义,而JS可以原生读取JSON这是一些Gtk代码示例:
from gi.repository import Gtk,WebKit
import json
w = Gtk.Window()
v = WebKit.WebView()
sw = Gtk.ScrolledWindow()
w.add(sw)
sw.add(v)
w.set_size_request(400,300)
w.connect("destroy", lambda q: Gtk.main_quit())
def window_title_change(v, param):
if not v.get_title():
return
if v.get_title().startswith("msgtopython:::"):
message = v.get_title().split(":::",1)[1]
# Now, send a message back to JavaScript
return_message = "You chose '%s'. How interesting." % message
v.execute_script("jscallback(%s)" % json.dumps(return_message))
v.connect("notify::title", window_title_change)
v.load_html_string("""<!doctype html>
<html>
<head>
<title>A demo</title>
<style>
body { font-family: Ubuntu, sans-serif; }
h1 { font-size: 1.3em; }
</style>
<body>
<h1>A tiny JavaScript demonstration</h1>
<form>
<p>What's your favourite thing about Jono? <select>
<option>------choose one------</option>
<option>his beard</option>
<option>his infectious sense of humour</option>
<option>his infectious diseases</option>
<option>his guitar ability</option>
<option>his wife</option>
</select></p>
</form>
<p id="out"></p>
<script>
document.querySelector("select").addEventListener("change", function() {
var chosenOption = this.options[this.selectedIndex].text;
// Now send that text back to Python by setting the title
document.title = "msgtopython:::" + chosenOption;
}, false);
function jscallback(msg) {
document.getElementById("out").innerHTML = msg;
}
</script>
</body>
</html>
""", "file:///")
w.show_all()
Gtk.main()
自从我玩了一段时间以来,这就是我所做的:
使用类似
<form>
<select onchange="location.href='mycombo://'+this.value">
<option>foo</option>
<option>bar</option>
<option>baz</option>
</select>
</form>
在您的HTML中。因此,当用户选择一个项目时mycombo
,将调用具有所选值的-URI。要捕获此消息,请将处理程序连接到WebView的navigation-requested
信号:
self.webview.connect("navigation-requested", self.on_navigation_requested)
在信号处理程序中,检查请求是否针对mycombo
URI。如果是这样,请致电on_combo_selected
:
def on_navigation_requested(self, view, frame, req, data=None):
uri = req.get_uri()
scheme, path=uri.split(':', 1)
if scheme == 'mycombo':
self.on_combo_selected(path)
return True
else:
return False
要更新WebView,请使用其execute_script
功能运行一些执行更新的JavaScript代码,例如:
self.webview.execute_script("document.title='Updated!';")
req
吗?