问题
I tried this in terminal and everything is OK, but if I run this inside script I can not insert JavaScript after gtk.main()
import gtk
import webkit
w = gtk.Window()
b = webkit.WebView()
w.add(b)
b.open('http://example.com')
w.show_all()
gtk.main() # this I don`t run inside terminal
#and after showing window I want to insert some JavaScript code
js = 'alert("a");'
b.execute_script(js)
How to solve this? Thanks in advance!
回答1:
Well, this problem is actually quite classic in GUI programming and so it is the solution. Direct actions (e.g. press a button) as well as indirect actions (webkit browser finishing loading a page) need always to fire up actions (functions) that sit on different processes or different threads.
In this case you can use the "load-finished"
event given by the webkit
object b
.
Once the web page has completed loading the associated function will fire up executing your JS code. This is what the code looks like:
def load_finished(webview, frame):
js = 'alert("a");'
b.execute_script(js)
b = webkit.WebView()
b.connect("load-finished", load_finished)
回答2:
gtk.main() will block until it receives a gtk.main_quit() is called or some other similar exit call. Afraid you'll have to do all javascript insertions using either callbacks or before you call gtk.main().
Surprised you managed to run gtk.main() without it blocking until you hit Ctrl+C in the terminal.
来源:https://stackoverflow.com/questions/11748404/python-gtk-webkit-insert-javascript-after-gtk-main