[Cordova] 用 cordova-plugin-ios-xhr 外掛解決 Origin null is not allowed by Access-Control-Allow-Origin 錯誤

[Cordova] 用 cordova-plugin-ios-xhr 外掛解決 Origin null is not allowed by Access-Control-Allow-Origin 錯誤

之前 [Cordova] App 在 iPhone 上出現 Origin null is not allowed 錯誤

那時用了 cordova-plugin-cors 這個外掛來解決,

不過留下了一個 session cookie 無法在頁面與 Ajax 連線間共用的問題…

 

今天讓 Cordova app 再連到另一個網站時,

發現 Origin null 的問題又跑出來了,重裝 cordova-plugin-cors 外掛也沒用,

只好再上網找找其他的解方…

後來看到了 cordova-plugin-ios-xhr 這個外掛,來看看吧~

 

1. 移除舊的 cordova-plugin-cors 外掛

先移掉現在好像無效的 cordova-plugin-cors 外掛:

cordova plugin rm cordova-plugin-cors

 

2. 安裝新的 cordova-plugin-ios-xhr 外掛

安裝新的外掛:

cordova plugin add @globules-io/cordova-plugin-ios-xhr

 

3. 修改 config.xml

要加入 config.xml 的設定有下面這些,

不過 cordova-plugin-ios-xhr 首頁並沒有多加解釋:

<preference name="NativeXHRLogging" value="full|none" />
<preference name="AllowUntrustedCerts"  value="true|false" />
<preference name="InterceptRemoteRequests" value="all|secureOnly" />
<preference name="CustomUserAgent" value="my_custom_user_agent" />
<preference name="allowFileAccessFromFileURLs" value="true|false" />
<preference name="allowUniversalAccessFromFileURLs" value="true|false" />

 

這是我加入 config.xml 的值:

<widget>
    <preference name="NativeXHRLogging" value="full" />
    <preference name="AllowUntrustedCerts"  value="true" />
    <preference name="InterceptRemoteRequests" value="all" />
    <preference name="allowFileAccessFromFileURLs" value="true" />
    <preference name="allowUniversalAccessFromFileURLs" value="true" />
</widget>

 

4. 編譯並執行 Cordova app

接著就照原本的流程,編譯並執行 Cordova app,

這時「大部分」的 HTTP/HTTPS 請求應該不會再遇到這種錯誤了:

[Error] Origin null is not allowed by Access-Control-Allow-Origin.
[Error] XMLHttpRequest cannot load https://xxx.com/yyy due to access control checks.
[Error] Failed to load resource: Origin null is not allowed by Access-Control-Allow-Origin.

 

為什麼說大部分呢?

因為藉由 Safari 開發者工具除錯 Cordova app 時,

還是可以在 Console 中看到一些錯誤。

像是在 Cordova app 裡連到 Dropbox 分享的檔案時,

雖然沒出現 Origin null 的錯誤,但會跑出 Origin file:// 的錯誤:

 

看起來像是外掛幫忙換掉 Origin 的內容,把值從 null 換成 file://,

因此如果網站只檢查有沒有值的話,就沒有問題。

但如果網站會檢查值是不是合理的話,也許就還是會被擋掉。

(↑ 以上只是猜測,錯了歡迎提供正確資訊 🙂 )

 

Session cookie 的問題,也還是存在的喔…

 

參考資料:

Wkwebview – Context issue – migrating from uiwebview to wkwebview

GitHub – oracle/cordova-plugin-wkwebview-file-xhr

(本頁面已被瀏覽過 952 次)

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *

這個網站採用 Akismet 服務減少垃圾留言。進一步了解 Akismet 如何處理網站訪客的留言資料