pyqt5.6 interceptRequest doesn't work

1k Views Asked by At

I want to interceptor a url request to another by subclass QWebEngineUrlRequestInterceptor:

class RequestInterceptor(QWebEngineUrlRequestInterceptor): 
    def interceptRequest(self,info): 
        print('#################interceptRequest')
        print(info.requestUrl(),info.firstPartyUrl(),info.NavigationType,info.resourceType(),info.requestMethod())
        if info.requestUrl().endswith("/jquery.js"):
           info.redirect('/jqueryTest.js')



app = QApplication([]) 
p = QWebEnginePage() 
v = QWebEngineView() 
v.setPage(p) 
p.profile().setRequestInterceptor(RequestInterceptor())
c.registerObject('bridge', p)
url = "http://127.0.0.1:8000/test.html?t=5"
v.setUrl(QUrl(url)) 
v.show() 
app.exec_()

When I run the code,the interceptor does not work!
Hope someone give me help,thanks!

PS: May It is caused by python garbage collection。So I store the interceptor in varible by modifying the code

p.profile().setRequestInterceptor(RequestInterceptor())

to

interceptor = RequestInterceptor()
p.profile().setRequestInterceptor(interceptor )

That's All.

2

There are 2 best solutions below

2
chunyisong On

Maybe it is caused by python garbage collection. So I store the interceptor in a variable by modifying the code:

p.profile().setRequestInterceptor(RequestInterceptor())

to:

interceptor = RequestInterceptor()
p.profile().setRequestInterceptor(interceptor )

That's All.

0
rayer456 On

Adding it as an attribute to the window object worked for me, indeed probably some garbage collection issue like mentioned here. The other solution here doesn't work for me.

self.interceptor = WebEngineUrlRequestInterceptor()
profile = QWebEngineProfile().defaultProfile()
profile.setUrlRequestInterceptor(self.interceptor)