注:如果不是和pyqt/PySide2直接相關程序,請查閱其他解決方案。
問題描述:
1.環境:PySide2, Python3.6.8,arcgis JavaScript API 4.14。
2.現象:新建HTML和js文件,通過arcgis JavaScript API 調用basemap。直接用瀏覽器打開HTML,運行正常,但是通過PySide2的QWebEngineView調用時,會報出如下錯誤:
*** has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’
header is present on the requested resource. If an opaque response
serves your needs, set the request’s mode to ‘no-cors’ to fetch the
resource with CORS disabled.
3.解決方法:在實例化
self.browser=QWebEngineView()
之後,需要調用:
self.browser.page().settings().setAttribute(QWebEngineSettings.LocalContentCanAccessRemoteUrls, True)
其作用是:允許本地加載的文檔忽略跨域規則,以便它們可以訪問通常會被阻止的遠程資源,因爲所有遠程資源都被視爲本地文件的跨域。 禁用此設置(默認)後,仍然可以使用跨域規則阻止的遠程訪問。 請注意,禁用此設置不會阻止XMLHttpRequests或本地文件中的媒體元素訪問遠程內容。 基本上,它僅停止某些HTML子資源,例如腳本,因此禁用此設置不是安全機制。