QWebEngineView javascript fetch CORS error but works on Chrome Desktop
Unsolved
QtWebEngine
-
Hi,
I try to use javascript "fetch" in my local html file. When I open the the following sample html in Chrome, it successfully fetch the json response without an error. But when the same file is opened via QWebEngineView it gives the following error:
js: Access to fetch at 'https://my-json-server.typicode.com/JSGund/XHR-Fetch-Request-JavaScript/posts' from origin 'file://' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, chrome-untrusted, https.
Is this due to the CHROMIUM_VERSION used in QWebEngineView, or is there any other reason?
HTML file with javascript fetch:
<!DOCTYPE html> <html> <head> <title>Fetch Request</title> </head> <body> <div> <h1>Article's by Jeetendra Gund</h1> <div id="blogs"></div> </div> <script> (function(){ fetch('https://my-json-server.typicode.com/JSGund/XHR-Fetch-Request-JavaScript/posts') .then(result => result.json()) .then(function (response) { var html = '<ol>'; response.forEach(function(dt){ html += '<li style="font-size:22px;"><a href="'+dt.path+'">'+dt.title+'</a></li>' }); html += '</ol>'; document.getElementById('blogs').innerHTML = html; }) .catch(function (error) { console.log('error', error); }); })() </script> </body> </html>
Python Qt application using PySide6 ver 6.2.2.1 and QWebEngineView:
import sys from PySide6.QtWidgets import * from PySide6.QtCore import QUrl from PySide6.QtWebEngineWidgets import * # set things up, and run it. :) if __name__ == '__main__': sys.argv.append("--remote-debugging-port=8001") app = QApplication(sys.argv) view = QWebEngineView() view.setUrl(QUrl("file:///fetch-request.html")) view.show() app.exec() sys.exit()
SOLUTION:
add the following beforeview.setUrl(QUrl("file:///fetch-request.html"))
view.page().settings().setAttribute(QWebEngineSettings.LocalContentCanAccessRemoteUrls, True)