Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print Javascript Exceptions In A QWebView To The Console

Tags:

python

qt

pyqt

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.QWebView()
browser.load(QtCore.QUrl("http://myurl"))
browser.show()

Thanks, Andrew

like image 725
Andrew Wilkinson Avatar asked Apr 26 '11 15:04

Andrew Wilkinson


2 Answers

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
like image 161
samplebias Avatar answered Oct 20 '22 18:10

samplebias


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)
like image 45
Rafael Oliveira Avatar answered Oct 20 '22 18:10

Rafael Oliveira