Print Javascript Exceptions In A QWebView To The Console
I'm using PyQt4 and a QWebView widget to view a webpage, but it appears as though there is a problem with my Javascript. Other browsers seem to run ok, so I would like to know if any exceptions are occurring by printing them to the console.
The code I'm using is below. What do I need to add to do this?
from PyQt4 import QtGui, QtWebKit
browser = QtWebKit.QWebV开发者_JAVA技巧iew()
browser.load(QtCore.QUrl("http://myurl"))
browser.show()
Thanks, Andrew
Create a subclass of QWebPage
and define the method javaScriptConsoleMessage()
:
import sys
from PyQt4 import QtCore, QtGui, QtWebKit
class WebPage(QtWebKit.QWebPage):
def javaScriptConsoleMessage(self, msg, line, source):
print '%s line %d: %s' % (source, line, msg)
url = 'http://localhost/test.html'
app = QtGui.QApplication([])
browser = QtWebKit.QWebView()
page = WebPage()
browser.setPage(page)
browser.load(QtCore.QUrl(url))
browser.show()
sys.exit(app.exec_())
Sample output:
% python qweb.py
http://localhost/test.html line 9: SyntaxError: Parse error
Or you could just set the DeveloperExtrasEnabled
setting. This will allow you to right-click the QWebView and select Inspect.
from PyQt5.QtWebKit import QWebSettings
QWebSettings.globalSettings().setAttribute(QWebSettings.DeveloperExtrasEnabled, True)
精彩评论