Iktedar
Iktedar

Reputation: 71

How to Call a method from inside executeScript method of inappbrowser

method to be called inside the executeScript like below.

function any-method(){ 
    alert("method called");
}

inAppBrowserRef.executeScript({ 
     code: "any-method()"
},executeScriptCallBack);

Upvotes: 1

Views: 1945

Answers (1)

DaveAlden
DaveAlden

Reputation: 30356

The string you pass as the code argument to executeScript is parsed and executed in the scope of the Webview which is opened inside of the InappBrowser window, which is a completely different Webview from that which your Cordova app is running in. Therefore you can't just share code between the Cordova app Webview and the InappBrowser Webview.

In the simple case you've illustrated, you'd need to inline the function into the code argument string:

inAppBrowserRef.executeScript({ 
     code: "(function(){ \
        alert(\"method called\"); \
     })();"
},executeScriptCallBack);

Note:

  • the backslash-escaped line endings enable you to split the string across multiple lines without needed to concatenate it with the + operator
  • any double quotes inside the string must be backslash-escaped
  • this will cause the alert to be displayed inside the InappBrowser Webview, not the Cordova app Webview

To display an alert in the context of the Cordova app Webview, you'd use the callback function parameter of executeScript, for example:

var a = 1,
    b = 2;

inAppBrowserRef.executeScript({ 
     code: "(function(){ \
        return "+a+"+"+b+"; \
     })();"
},function(values){
    var result = values[0];
    alert("Result: "+result); // Result: 3
});

If the function you're calling already exists in the page being loaded into the InappBrowser, you can of course call it and return values from it:

iab_page.html:

<!DOCTYPE html>
<html>
    <head>
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
    </head>
    <body>
        <script type="text/javascript">
            function getResult(x, y){
                return x + y;
            }
        </script>

        <h1>Inappbrowser content page</h1>
    </body>
</html>

Cordova app code:

var a = 1,
    b = 2;

var inAppBrowserRef = cordova.InAppBrowser.open('iab_page.html', '_blank');

inAppBrowserRef.addEventListener('loadstop', function (e) {
    inAppBrowserRef.executeScript({ 
         code: "getResult("+a+","+b+")"
    },function(values){
        var result = values[0];
        alert("Result: "+result); // Result: 3
    });
});

Upvotes: 2

Related Questions