Search code examples
cordovacordova-plugins

Unable to access window.cordova.plugins from Cordova app


I'm having trouble with my Cordova application accessing window.cordova.plugins with Javascript.

When my app starts, the webview immediately redirects using the following, meaning I no longer have access to window.cordova.plugins:

window.location.href = "https://www.example.com/";

Previously I remedied this using cordova-plugin-remote-injection which injected Cordova and any other Javascript files I needed, but I have found it now interferes with regular Javascript on my site (primarily Apple Pay on the web). Additionally the plugin has been deprecated so doesn't receive updates.

Can someone suggest a current and preferably future proof way of being able to access window.cordova.plugins from my remote site? This would need to work on both ANDROID and IOS.

Thanks!


Solution

  • Although it's not an ideal solution, I've solved the problem by uploading the Cordova Javascript files to my web server, and included them into my webpage. Cordova as well as all plugins are now accessible.

    For anyone wanting to do the same:

    • In your platforms/<platform>/platform_www/ directory, upload "cordova.js", "cordova_plugins.js" and the "plugins" folder to your server.
    • Upload any additional Javascript/CSS/etc. files that you may need. (anything you need that's custom to the app).
    • On your page, create a <script> tag that loads "cordova.js".

    That's all. "cordova.js" loads "cordova_plugins.js" which in turn loads all accompanying plugin Javascript files.

    The reasons why it's not an ideal solution:

    • Everytime I release a new build of the app, I will need to upload the rebuilt Javascript files just in case they have changed.
    • I need to keep many different versions of the files on the server to cater for anyone that hasn't yet updated their app. eg. 1.4/android/, 1.4/ios/, 1.5/android/, 1.5/ios/, etc. and the server has to know to serve the correct files based on the app version (which I have stored in a cookie).
    • There will be a slight performance overhead because of the HTTP(S) requests that now need to be performed by the app, not to mention the server having to process the additional requests.
    • If you were hoping to hide the fact that your app isn't just a webpage disguised as an app, you're out of luck. It's now public information.

    All said, it does seem to work.