Nov 10, 2015

Use ngCordova inAppBrowser executeScript interacting with remote WebView content

Even the idea/solution very straight forward, but still, I learned ngCordova's inAppBrowser the hard way.

I am using cordovaInAppBrowser to handle my remote content in mobile's WebView.
Tutorials accessible out there mostly give you the idea of how it works in direct content display, like:


// insert Javascript via code / file
$cordovaInAppBrowser.executeScript({
  code: 'alert("some text in the webview");'
});


Yes, it does tell the code is working in the webview,
but my problem is how can the value be manipulated and pass back to our cordova app?
So what we need is more than pop up alert box in webview.

As I learned,

  1. executeScript code WOULD JUST work when we have target as "_blank"

    // executeScript must has "_blank" as target
    $cordovaInAppBrowser.open(YOUR_URL, '_blank');
    

  2. the executeScript code would just run once as inAppBrowser page load/refresh depend on the events triggered:
    • $cordovaInAppBrowser:exit
    • $cordovaInAppBrowser:loaderror
    • $cordovaInAppBrowser:loadstop
    • $cordovaInAppBrowser:loadstart

So what you can do with this executeScript feature is to 'grab' your expected variable.

$rootScope.$on('$cordovaInAppBrowser:loadstop', function(e, event){
  $cordovaInAppBrowser.executeScript({
    code: "var executable = function(data) { return data; }; executable(yourJsVariable || null);"
  }).then(function(data) {
    // Do something here with your obtained value
    if (angular.isObject(data)) {
      console.log(data);
    }
  });
});

In my case above, my detection of yourJsVariable starts as the page load of the inAppBrowser stops.

Reference: Issue injecting external script with executeScript method in Cordova
(The reference above is the best working example code I found so far.)

No comments:

Post a Comment

Hey, thank you for spending time leaving some thoughts, that would be really helpful as encouragement for us to write more quality articles! Thank you!