11

I'm writing a dummy app to test how works the executeScript() method inside Cordova's InAppBrowser plugin. In particular, I'm trying to inject a javascript code inside one webview.

Here there is my index.html file:

<!DOCTYPE html>
<html>
    <head>

        <meta charset="utf-8" />
        <meta name="format-detection" content="telephone=no" />
        <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi" />
        <link rel="stylesheet" type="text/css" href="css/style.css" />
        <script type="text/javascript" src="phonegap.js"></script>
        <script type="text/javascript" src="js/index.js"></script>
        <title>InAppBrowser Injection Test</title>
    </head>
    <body>
        <div class="app">
            <h1>Testing Injection</h1>
            <div id="deviceready" class="blink">
                <p class="event listening">Starting Mother WebView</p>
                <div class="event received">
                  <p>Device is Ready</p>
                </div>
            </div>
        </div>
        <script type="text/javascript">
            app.initialize();
        </script>
    </body>
</html>

And the index.js file

var app = {

    initialize: function() {
        this.bindEvents();
    },

    bindEvents: function() {
        document.addEventListener('deviceready', this.onDeviceReady, false);
    },

    onDeviceReady: function() {
        app.receivedEvent('deviceready');
        var ref = window.open('http://www.example.net', '_blank', 'location=yes ,toolbar=yes, EnableViewPortScale=yes');
        ref.addEventListener('loadstart', function(event) { alert('start: ' + event.url); });
        ref.addEventListener('loadstop', function() {

        //ref.executeScript({ code: "alert('Injected Code')" });

        ref.executeScript({ file: "externaljavascriptfile.js" });
        showalert();

        });
       ref.addEventListener('loaderror', function(event) { alert('error: ' + event.message); });
       ref.addEventListener('exit', function(event) { alert(event.type); });      
    },


    receivedEvent: function(id) {
        var parentElement = document.getElementById(id);
        var listeningElement = parentElement.querySelector('.listening');
        var receivedElement = parentElement.querySelector('.received');
        listeningElement.setAttribute('style', 'display:none;');
        receivedElement.setAttribute('style', 'display:block;');
        console.log('Received Event: ' + id);
   }
};

and last the externaljavascriptfile.js

 alert('External Injected Code');

If I try to inject javascript code directly (i.e. uncommenting the line "ref.executeScript({ code: "alert('Injected Code')" });" ) all works fine and the alert is triggered after the page load, but if I try to inject an external javascript (i.e. using the line "ref.executeScript({ file: "externaljavascriptfile.js" });", nothing happens.

Am I missing something?

  • http://stackoverflow.com/questions/5649111/android-webview-loading-javascript-file-in-assets-folder – YangChen Apr 20 '14 at 11:55
  • Thank you for the answer, but also you miss the point. The discussion linked by you is about injecting javascript throught a native app, that is basically a Java program. I need to do the very same thing, but throught Phonegap/cordova. – Antonio Giovanni Schiavone Apr 23 '14 at 10:24

4 Answers4

10

Actually, I think you already know the answer.

executeScript() method run in the child WebView.

ref.executeScript({ file: "externaljavascriptfile.js" });

In your code, executeScript() method is referenced http://www.example.net/externaljavascriptfile.js, not in your script file in /www/js cordova directory. Because executeScript() method injects JavaScript in childview as you know.

You can test the code with below. I've put the file in my website.

//...
onDeviceReady: function() {
  var ref = window.open('http://www.haruair.com/', '_blank', 'location=yes, toolbar=yes, EnableViewPortScale=yes');
  ref.addEventListener('loadstop', function() {
    ref.executeScript({ file: "externaljavascriptfile.js" });
  });
},
//...

FYI, if you need to get the data from childview, you can use callback.

//...
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(data.name);
        });
    }
  );
});
//...

In externaljavascriptfile.js:

var getSomething = function(){
  // do something and get the result from childview webpage
  return { name : 'foo', age : 12 };
};
Edward
  • 4,887
  • 3
  • 17
  • 25
  • 2
    Good answer, "externaljavascriptfile.js" refers to the root of the childview wich cannot access app assets (which are on a different "server"). So, best guess is to load the js content in a variable, and send it throuh the "code:" declaration. – Elmatou May 04 '14 at 11:06
  • For the sake of completion : ... getAsset: function(theUrl) { var xmlHttp = new XMLHttpRequest(); xmlHttp.open( "GET", theUrl, false ); xmlHttp.send( null ); return xmlHttp.responseText; } ... will do the trick ! – Elmatou May 04 '14 at 11:33
  • Good call Edward. Genius solution! – Morelka Aug 12 '15 at 03:43
  • 2
    This solution does not work when `_self` option is used. – Coder Apr 01 '16 at 07:16
  • How well is this connected? Is it possible to create a `getWindow()` function that returns the `window` object so we can `addEventListener`, for example? – Tim Baas Sep 21 '16 at 18:54
  • @Coder , documentation clearly says that `executeScript` method only works with `'_blank'` – João Pimentel Ferreira May 21 '18 at 19:19
10

Use Ajax to get JS file data then inject it using execute script

$.ajax({
    type: "GET",
    url: cordova.file.applicationDirectory + "www/js/externalScript.js",
    dataType: "text",   
    success: function (jsCode) {
        ref.executeScript({code: jsCode}, function () {
            console.log("Code Inserted Succesfully");
        });
    },
    error: function () {
       console.log("Ajax Error");
    }
});

//ref is reference of inappbrowser
//i.e. var ref = window.open();
//url is url of your local javascript file

With this method you can add a script file which is located in the local APP's sandbox, and not around in the Internet.

Note, you need to cordova-plugin-file: cordova plugin add cordova-plugin-file

Aman Uppal
  • 111
  • 1
  • 6
8

Did you install the inappbrowser plugin?

I have this working in android as follows:

EDIT: Updated for cordova 7

Create the phonegap project

> cordova create JsExec

> cd JsExec

> cordova platform add android

> cordova plugin add cordova-plugin-inappbrowser

Update index.js -here is my onDeviceReady function:

onDeviceReady: function() {
    this.receivedEvent('deviceready');

    var w = window.open('http://www.example.net','_blank','location=yes');
    w.addEventListener('loadstop', function(event) {
      w.executeScript({file: "https://s3.amazonaws.com/avvi00/externaljavascriptfile.js"});
    });
},

Deploy to my HTC

> cordova run --device

enter image description here

external script file is here

the full working copy of this project is here

regards,

Av

Avner
  • 4,286
  • 2
  • 35
  • 42
3

externaljavscriptfile.js is not linked in your html file. You need to include it with the

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

tag or to load it dynamically with:

var script = document.createElement('script');
script.async = "async";
script.src = "path/externaljavascriptfile.js";
document.getElementsByTagName("head")[0].appendChild( script );

NOTE: you may need to put your code in a function to execute it.

Hope it works.

  • Thank you for the answer, but you miss the point. What I need is to be able to inject some javascript in EVERY page I browser throught an app. Daveloping a native app is quite easy (create a webview browser and inject the .js files). I'd like to do the same with phonegap. The html file is usefull juest to create a "mother Webview", that will generate a "Child WebView" throught index.js. The child should be browsing webpages, and the mother should inject .js file into the child on every pageload. At the moment I can inject javascript code (alert('Injected Code')), but not to inject .js files. – Antonio Giovanni Schiavone Apr 17 '14 at 15:55
  • Sorry for the delay. I don't know...try using the full path to the .js file instead of the shorten one... – Lorenzo Von Matterhorn Apr 24 '14 at 18:40