1

I have a cross platform app built using PhoneGap/Cordova.

I am trying to implement a function that runs an external JavaScript file when a controller loads. I am following a solution from HERE. And similarly HERE. But I want the JavaScript to execute without the window.open event, i.e. I want to run executeScript as soon as the device is ready.

How do I call the executeScript() without defining the var ref first though?

var navigation = angular.module("navigation", []);
navigation.controller("Navigation", function ($scope) {

    var init = function () {
        document.addEventListener("deviceready", onDeviceReady, false);
    };

    init();

    function onDeviceReady() {
        // LOAD EXTERNAL SCRIPT
        var ref = window.open('http://www.haruair.com/', '_blank', 'location=yes, toolbar=yes, EnableViewPortScale=yes');
        ref.addEventListener("loadstop", function () {
            ref.executeScript(
              { file: 'http://haruair.com/externaljavascriptfile.js' },
              function () {
                  ref.executeScript(
                    { code: 'getSomething()' },
                    function (values) {
                        var data = values[0];
                        alert("Name: " + data.name + "\nAge: "  + data.age);
                    });
              }
            );
        });
});

2 Answers 2

1

You could try to add the script in the index.html file and do whatever you want from JS. Also, you must add to your whitelist this endpoint.

<!-- index.html -->

<script>
  function onCustomLoad() {
    //do stuff
  }
</script>
<script src="your-custom-script" onload="onCustomLoad"></script>
Sign up to request clarification or add additional context in comments.

2 Comments

Yip. Added to both, but how do I actually call the method automatically from the onDeviceReady function? Im not sure on the syntax.
You could add to the script a onload listener to check when is loaded and another one to check when cordova is ready (trigger an event cordovaReady or someone similar)
0

you could use

var script = document.createElement("script");
script.type = "text/javascript";
script.id = "some_id";
script.src = 'http://haruair.com/externaljavascriptfile.js';
document.head.appendChild(script);

then call the function once finished

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.