Search code examples
javascripthtmlcordovawebviewcordova-plugins

How to import JavaScript variable in HTML script tag


I'm working on a hybrid app with Cordova but my little experience with JavaScript doesn't let me handle this.

I created a Cordova plugin which includes the plugin.js file

var exec = require('cordova/exec');

var PLUGIN_NAME = 'MyCordovaPlugin';

var MyCordovaPlugin = {
  echo: function(phrase, cb) {
    exec(cb, null, PLUGIN_NAME, 'echo', [phrase]);
  },
  getDate: function(cb) {
    exec(cb, null, PLUGIN_NAME, 'getDate', []);
  }
};

module.exports = MyCordovaPlugin;

Since it's been exported, I'm trying to use MyCordovaPlugin variable in my index.html

<!DOCTYPE html>
<html>
<head>
    <title>JavaScript View</title>
    <script type="text/javascript">
        function createTransaction(){
            window.MyCordovaPlugin.echo('echo', function() { 

            });
            return false;
        }
        window.onload = function(){
            var form = document.getElementById("form");
            form.onsubmit = createTransaction;
        }
    </script>
</head>
    <body>
        <form id="form">
            <input type="submit" value="Create transaction" />
        </form>
    </body>
</html>

How can index.html have access to the variable?


Solution

  • To make Cordova plugins accessible you have to import the cordova.js in your index.html:

    <script type="text/javascript" src="cordova.js"></script>