Skip to content

Instantly share code, notes, and snippets.

@fmarani
Created December 5, 2014 08:47
Show Gist options
  • Save fmarani/55693f9477cab302116d to your computer and use it in GitHub Desktop.
Save fmarani/55693f9477cab302116d to your computer and use it in GitHub Desktop.
python webkit integration test
import sys
from PySide.QtCore import QObject, Slot, QTimer
from PySide.QtGui import QApplication
from PySide.QtWebKit import QWebView, QWebPage
import logging
html = """
<html>
<body>
<h1>Hello!</h1><br>
<div id="box"></div>
<input type="text" id="text">
<h2><a href="#" onclick="printer.text(document.getElementById('text').value)">QObject Test</a></h2>
<h2><a href="#" onclick="alert('Javascript works!')">JS test</a></h2>
<h2><a href="#" onclick="blabla('Javascript works!')">JS broken test</a></h2>
</body>
</html>
"""
class ConsolePrinter(QObject):
def __init__(self, parent=None):
super(ConsolePrinter, self).__init__(parent)
@Slot(str)
def text(self, message):
print message
class WebPage(QWebPage):
"""
Makes it possible to use a Python logger to print javascript console messages
"""
def __init__(self, logger=None, parent=None):
super(WebPage, self).__init__(parent)
if not logger:
logger = logging
self.logger = logger
def javaScriptConsoleMessage(self, msg, lineNumber, sourceID):
self.logger.warning("JsConsole(%s:%d): %s" % (sourceID, lineNumber, msg))
if __name__ == '__main__':
def update():
frame.findFirstElement("div").appendInside("TICK ")
app = QApplication(sys.argv)
view = QWebView()
view.setPage(WebPage())
frame = view.page().mainFrame()
printer = ConsolePrinter()
timer = QTimer(app)
timer.timeout.connect(update)
timer.start(1000)
view.setHtml(html)
frame.addToJavaScriptWindowObject('printer', printer)
view.show()
app.exec_()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment