Hybrid app with remote html and local cordova.js

I have a website that I want to enhance on mobiles with a hybrid app. Ideally the app would load the remote site over http but load the platform specific code locally. I've tried to set up a Cordova project to do this but am having lots of trouble. Cordova 4.3.1, Cordova Android 3.7.2 on a Nexus 7 Android 4.4.4 has been my environment. (The google maps plugin is for Cordova Android < 4.)

If I try to load file:///android_assets/www/cordova.js from an http site, chromium says Not allowed to load local resource. I tried to set up a local URL scheme but don't know what android-specific code to put where.

Is this the right way to make a hybrid app? Is there a cordova plugin to allow loading file: from http:?


I also tried using an iframe and passing messages to indicate cordova is enabled and which plugins are installed, but I don't want to deal with having the http server re-serve the same js files that are already available locally.

I also thought to download the website and access it over file: but I imagine I will have the same problem trying to access http resources.

I am able to load local cordova.js on remote html using cordova-plugin-file (cdvfile://) plugin .

  1. Add cordova-plugin-file plugin to your cordova project https://cordova.apache.org/docs/en/latest/reference/cordova-plugin-file/

  2. Confirm cdvfile URI for cordova.js using below sample code(Android example)

    checkCordovaJSPath('file:///android_asset/www/cordova.js');
    
    function checkCordovaJSPath(jsUri) {
            window.resolveLocalFileSystemURL(jsUri, function success(fileEntry){
                console.log("got cordova.js file: " + fileEntry.fullPath);
                console.log('cordova.js cdvfile URI: ' + fileEntry.toInternalURL());
               
    });
    }

Apache Cordova Tutorial: Mobile Apps with HTML, CSS, and JS , Apache Cordova Tutorial: Developing Mobile Applications with Cordova In this case, the output file for Android will contain both the app.js and android.js For now, let's try SQLitePlugin which provides you with a local SQLite database. You can easily debug Android applications through the Chrome remote debugger. in Chap 9, section "Developing Hybrid Remote Apps," is the traditional advice, "For hybrid remote applications, you are no longer required to host cordova.js or any plug-ins on the server. Instead, you can include cordova.js as https://localhost/cordova.js in your HTML source." This is what we've always done (and are currently doing).

I don't know if this is the right way to make a hybrid app, but I got it working by serving assets over http with https://github.com/floatinghotpot/cordova-httpd .

On the local page bundled with the app I have added:

    <script type="text/javascript">
        document.addEventListener("deviceready", function () {
            var httpd = cordova.plugins.CorHttpd;
            httpd.startServer({
                'www_root': '',
                'port': 8080,
                'localhost_only': false
            }, function (url) {
                // if server is up, it will return the url of http://<server ip>:port/
                // the ip is the active network connection
                // if no wifi or no cell, "127.0.0.1" will be returned.
                document.getElementById('url').innerHTML = "server is started: <a href='" + url + "' target='_blank'>" + url + "</a>";
                location.replace('http://192.168.0.134:9090/homechooser/beta/#' + JSON.stringify({'cordova.js': url + '/cordova.js'}));
            }, function (error) {
                document.getElementById('url').innerHTML = 'failed to start server: ' + error;
            });
        }, false);
    </script>
    <div id="url"></div>

Then on the remote webpage I have added:

(function () {
    var hash;
    if (location && location.hash)
        try {
            hash = JSON.parse(location.hash.substring(1));
        } catch (e) {
        }
    if (hash && hash['cordova.js'])
        $.getScript(hash['cordova.js'], function () {
            alert("Running cordova.js");
        });
})();

now to see if cordova can actually be used this way...

Hybrid app with remote html and local cordova.js, I have a website that I want to enhance on mobiles with a hybrid app. Ideally the app would load the remote site over http but load the platform� Usually when you make an Hybrid Application you point your WebView start url to a local html page available in your package that include cordova.js, but with Hosted Hybrid Application your WebView start url point to your remote web site.

The cdvfile solution will not work for active content (js files) because of the mixed content policy. Here is how to make it work:

For android: Disable mixed content policy by putting the following code inside the pluginInitialize method of your cordova plugin:

if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
            final WebSettings settings = ((WebView)this.webView.getView()).getSettings();
      settings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        } 

https://developer.android.com/reference/android/webkit/WebSettings.html#MIXED_CONTENT_ALWAYS_ALLOW)

Then include local cordova.js using:

<script src="cdvfile://localhost/assets/www/cordova.js"></script>

For ios: I submitted a PR to the file plugin which solves the mixed content problem on ios: apache/cordova-plugin-file#296 The fixed version is available at: https://github.com/guylando/cordova-plugin-file If you load a remote site https://example.com on the webview then it allows to access local files using the url: https://example.com/cdvfile/bundle/www/cordova.js instead of cdvfile://localhost/bundle/www/cordova.js And by this solves the mixed content problems

Include local cordova.js using:

<script src="/cdvfile/bundle/www/cordova.js"></script>

Cordova: Navigating to local content from a Website, I've been writing about pointing a Cordova app at a remote website. The html, css, and javascript packaged inside the Cordova app allows users to input their file:///var/mobile/Containers/Bundle/Application/{{uid}}/com. of “cdvfile://” that can be used as a access device resources such as cordova.js. Now, when the Cordova app loads the remote web content, the app executes the setPlatformCookie function to tell the web server that a Cordova app is requesting the content. The URL also passes in the the platform identifier ( cordova.platformId ), you'll use this later for redirection.

Thing is your are trying to load a web-url on the local hosted app, imagine doing the same thing on Native Android App, what would you do? you will place a web-client or a web-browser in your app. But Cordova/Phonegap already uses Web-Browser to render your pages. So its like a using web-browser inside a web browser.

You need to install InAppBrowser which will give you the ability to load 3rd party hosted web pages.

Sample Code

  document.addEventListener("deviceready", onDeviceReady, false);

    // device APIs are available
    //
    function onDeviceReady() {
         var ref = window.open('http://yourWebPage.com', '_blank', 'location=yes');
         ref.addEventListener('loadstart', function(event) { alert('start: ' + event.url); });
         ref.addEventListener('loadstop', function(event) { alert('stop: ' + event.url); });
         ref.addEventListener('loaderror', function(event) { alert('error: ' + event.message); });
         ref.addEventListener('exit', function(event) { alert(event.type); });
    }

Loading cordova.js from a WebSite | by Michael Barshinger, Cordova apps are typically made up of html, css, and javascript possible to create Cordova apps that load content remotely from a web server. combination with cordova-plugin-httpd to serve the “own” local files that The idea of having a single code base for web browsers and mobile apps is tempting. Framework7 is a free and open source mobile HTML framework for developing hybrid mobile apps or web apps with iOS & Android native look and feel. Evothings Studio Evothings Studio provides Cordova developers with a rapid development workflow, tutorials and example apps for the Internet of Things.

Run Your Hosted Web App in an Apache Cordova App, The Cordova mobile client app works on Android, iOS, and Windows 10. executes in the remote web application, not the local Cordova application code. In Solution Explorer, double-click on the project's www\index.html file For the web application to run plugin code, the platform's cordova.js as well as� Hybrid-local, where you install your html and js files locally or Hybrid-remote, where you put everything in the cloud as visual force pages and static resources. The webinar explained that if you wanted offline smartstore you need to use the hybrid-local approach and that it is difficult to use offline in the hybrid-remote approach.

Get Started with Hybrid Development Unit, Build Cordova-based hybrid mobile apps using HTML5 and Salesforce These apps are developed with the force.js library and store their HTML, Hybrid remote—Hybrid remote apps deliver Visualforce pages through the mobile Once you're ready to move forward, you create and explore a basic hybrid local app. Apache Cordova - Build Hybrid Mobile Apps with HTML CSS & JS. Course Ratings are calculated from individual students’ ratings and a variety of other signals, like age of rating and reliability, to ensure that they reflect course quality fairly and accurately.

Launch a website as a mobile app using PhoneGap/Apache Cordova, A basic Cordova app gives you a way to launch the app with an HTML page that you use to (I've called it local), and do everything in option 2 to load the remote site is cordova.js on the remote mobile website or in the local cordova app? if� [S]he believes that cordova.js, which is present in the app after Build, should be injected into that website. Now, this can be done by using the iab-plugin's executeScript method to insert a reference to cordova.js. Since that file is not present on the server where the site comes from, the full local file path must be specified to reference it.

Comments
  • How did you solve it eventually?
  • @user2335065 stackoverflow.com/a/31019431/192798 i gave up and put the file: resources on http:.
  • For anyone searching for this issue.. the below guide works: docs.microsoft.com/en-us/visualstudio/cross-platform/…
  • your solution is hard to follow, compared to pramoda's answer. see the answering guidelines: stackoverflow.com/help/how-to-answer , particularly "Always quote the most relevant part of an important link, in case the target site is unreachable or goes permanently offline."
  • can you elaborate on "your cordova plugin"? i'm writing a cordova app, not a plugin.
  • My personal conclusion is that cordova does not always have a plugin for everything and the plugins environment is built by very few individuals which mostly didn't update their repositories for years. If you want to use latest android/ios features you have no choice but to add your own plugin and in that plugin you will be able to insert any ios and android code for all the features you want which aren't available in other plugins.
  • Also this has a big performance benefit because adding a new plugin for every small thing makes the app performance slower because every plugin requires its javascript file to be loaded on app start.
  • Replace the npm package name with the url of the github repository in the normal plugin addition command
  • but that won't allow yourWebPage.com to use cordova.js
  • oh but that gives me an idea to use ref.executeScript(details, callback); to load cordova.js in yourWebPage.com. will try it and let you know.
  • offcourse thats intended. If you use google.com inplace of yourWebPage.com then why Google.com allow your js to run on his webpage ?
  • executeScript injects your script locally in your browser, not in the webpage.
  • i don't want to use google.com. i want to use yourWebPage.com and i want it to access cordova.js. i allow cordova.js to run on my web page because i trust it. chromium is putting security in the other way. it's not allowing access to file: because it doesn't trust http:.