Disable internet access for QtWebKit.QWebView, and only allow file urls

416 Views Asked by At

I'm making my first app in PySide, PyQt or Qt, and I need to block the network access of my app to prevent security risks. This is my code:

#!/usr/bin/python
import sys,os;
from PySide import QtCore, QtGui, QtWebKit;
app = QtGui.QApplication(sys.argv);
view = QtWebKit.QWebView();
view.load(QtCore.QUrl.fromLocalFile("./index.html"));
view.settings().setAttribute(QtWebKit.QWebSettings.WebAttribute.DeveloperExtrasEnabled, True);
view.settings().setAttribute(QtWebKit.QWebSettings.LocalContentCanAccessRemoteUrls, False);
view.show();
sys.exit(app.exec_());

I'm using this line to block the network access:

view.settings().setAttribute(QtWebKit.QWebSettings.LocalContentCanAccessRemoteUrls, False);

But it does not work: when I open the console in inspect, and I use this js command:

window.location.href = "http://google.com";

the page http://google.com is loaded anyway. How can I block internet access to my app? Something like this example:

view = QtWebKit.QWebView();
view.settings().setAttribute(QtWebKit.DisableNetworkAccess, True);

How can I do something similar to that, or another alternative?

(Note: you can answer for Qt C++ too, I'm using both languages, Python and C++).

2

There are 2 best solutions below

0
Seth On

If you don't need Javascript, you can prevent navigating away by disabling it with view.settings().setAttribute(QtWebKit.QWebSettings.JavascriptEnabled, False).

0
ekhumoro On

You can disable all internet access via the network-access-manager of the view's page:

from PySide import QtNetwork
...
view.page().networkAccessManager().setNetworkAccessible(
    QtNetwork.QNetworkAccessManager.NotAccessible)

This still allows access to file:// urls, but all other schemes will produce an error-message.