Search code examples
javascriptcordovaionic-frameworkinappbrowser

How to inject HTML to page with Cordova's InAppBrowser


I'm running single page web app inside InAppBrowser. I want to inject HTML attributes into some HTML elements. For example change all h1 to h2.

I know I can use executeScript method for short tasks like this:

win.executeScript({ code: "console.log( 'hello' );" })

Does anybody know what is the best way to run longer script with executeScript method and how to make sure it runs after everything is loaded?


Solution

  • If you want to inject a lot of code you should use a js file instead of using just a code string. To inject code from a .js file and making sure the page is loaded you have to run executescript when the loadstop event is called, something like this:

    var ref = cordova.InAppBrowser.open('http://apache.org', '_blank');
    ref.addEventListener('loadstop', function() {
        ref.executeScript({file: "http://www.yourwebsite.com/myscript.js"});
    });
    

    file has to be an external js if you are loading an external website, but can be a local js if you are loading a local html file